I am trying to send an email with a specific "layout" (for header/footer) with a specific template (main view of the email, e.g. 2-column layout etc.).
The $mainView
html has: <?= $this->content ?>
but this is always NULL when it should be the $childView
html with all variables.
Here is what I have in a MailService.php
file:
public function createMessage($to, $subject, $template, $variables) : Message
{
// Create mail
$message = new Message();
// Create mail body
$mainView = new ViewModel();
$mainView->setTerminal(true);
$mainView->setTemplate('layout/mail.phtml');
$childView = new ViewModel();
$childView->setTerminal(true);
$childView->setTemplate($template);
$childView->setVariables($variables);
$mainView->addChild($childView, 'content');
$msgRender = $this->viewRenderer->render($mainView);
$body = new Part($msgRender);
$body->setType(Mime::TYPE_HTML);
$messageBody = new MessageBody();
$messageBody->addPart($body);
$message->setBody($messageBody);
$message->setTo($to);
$message->setSubject($subject);
return $message;
}
$this->viewRenderer
is injected in the Factory:
/** @var RendererInterface $viewRenderer */
$viewRenderer = $serviceLocator->get('viewrenderer');
Ok I got it working ! :) I had to render the childView
then set this render as the view variable for the mainView
public function createMessage($to, $subject, $template, $variables) : Message
{
// Create mail
$message = new Message();
// Create mail body
$mainView = new ViewModel();
$mainView->setTerminal(true);
$mainView->setTemplate('layout/mail.phtml');
$childView = new ViewModel();
$childView->setTemplate($template);
$childView->setVariables($variables);
$childRender = $this->viewRenderer->render($childView); // render child
$mainView->setVariable('content', $childRender); // set childRender to mainView
$msgRender = $this->viewRenderer->render($mainView);
$body = new Part($msgRender);
$body->setType(Mime::TYPE_HTML);
$messageBody = new MessageBody();
$messageBody->addPart($body);
$message->setBody($messageBody);
$message->setTo($to);
$message->setSubject($subject);
return $message;
}