ZF2: Using Zend\View to render emails

936 views Asked by At

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.

1

There are 1 answers

0
Mohammad Mehdi Habibi On BEST ANSWER

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);