ZF2: Using Zend\View to render emails

email, zend-framework2, zend-view

Solution

You need `ServiceManager` to do this. Try this in your Controller:

$view = new ViewModel(array(
        'foo'=>'bar',           
));
$view->setTemplate('path/to/phtml');
$view->setTerminal(true);
$serviceManager = $this->getServiceLocator();
$emailBody = $serviceManager->get('ViewRenderer')->render($view);

Problem

In ZF1, I used the view component to render email templates as follows: ``` $html = new Zend_View(); $html->setScriptPath($path); $html->assign($vars); $body = $html->render($template); // prepare the mail $mail = new Zend_Mail('utf-8'); $mail->setBodyHtml($body); ``` How do I go about this in ZF2? I think I need to create a new ViewModel, assign my variables and set the template, but where to from there? Note that I am not doing this in the controller. I have seen this question, ZF2 view rendering, where the html is returned in the MVC response, but I am looking to render a template and store the result in a variable (which I then assign to the email body). I would do this in a service layer. The view instance which is related to the MVC process would be unrelated to the instance I use to render the email body.

Original source