In the ZF1 I used the following code to render a mail body:
// View erstellen
$view = new Zend_View();
// Layout erstellen
$layout = new Zend_Layout();
// HelperPath muss hier nochmals übergeben werden da es ein neues View Objekt ist.
$view->addHelperPath('Own/View/Helper', "Own_View_Helper_");
// ViewScript
$view->setScriptPath(APPLICATION_PATH . '/views/scripts/emails/');
// LayoutPath
$layout->setLayoutPath(APPLICATION_PATH . '/layouts/scripts/');
$layout->setLayout('layoutMail');
$layout->setView($view);
foreach ($assigns as $key => $value) {
$view->assign($key,$value);
}
$layout->content = $view->render($templateName);
return $layout->render();
I tried a lot but I cannot realise this function in ZF2. My actual code is this. But it uses the standard layout and I cannot get it in a string.
public function mailAction()
{
$viewModel = new ViewModel();
$viewModel->setTemplate("zhorty/test");
$viewModel->setVariable('test', 'some value');
return $viewModel;
}
My answer is based on user1986560's answer and How to Render a custom view with plugins in Zend Framework 2. I'm adding it as I think it makes things a little easier to implement.
I have an email layout and different content files. The layout can be reused and different content files added.
view/email/layout.phtml
view/email/contact.phtml
In your modules conf, add the layout and different content files. By doing it this way, you can use view helpers.
module.config.php
In your controller/action:
Hopefully one of my blog post will help you out, it is about how to use Zend\View as template in Zend\Mail and add attachments in ZF2
It is written by Chinese, but I think just read the code is clear enough. Also you could read it with help of Google translation
For sendig Emails I recommend the following Module: https://github.com/WasabiLib/Mail
The Module is based on the ZF2 message and it is configured as a service. So you only need to call the servicemanager.
The body method is able to handle ZF2 viewModels. See the example below:
It is bundled with a responsive email template that you can customize. You only need to add the module to the application.config.php and you are ready to go.
Thank you! Your answer helped me!
I extended the code. So I can use a layout template as well.
@user1986560 answer is not complete, cause you must need some basic helper like "url" with router and sometimes "basePath" also required.
Here is the complete code -
Hope it my help someone.