Search code examples
phpzend-frameworkzend-layout

How to use a layout for emails in Zend Framework


I would like to use a layout for the emails I'm sending out. I'm currently usine Zend Layout for the web pages, but would like to theme my emails as well.

Here is what I've tried.

This is my function that sends the email

    $layout = Zend_Layout::getMvcInstance();
    $this->_view->render($template);
    $html = $layout->render('email');
    $this->setBodyHtml($html,$this->getCharset(), $encoding);
    $this->send();

The email layout is simply

    The email content
    <?php echo $this->layout()->content; ?>

When it comes through as an email it just has...

    The email content

Solution

  • You're pretty close in your original method; however, you have to perform a couple extra steps on Zend_Layout to get what you want:

    $layout = Zend_Layout::getMvcInstance();
    $layout->setLayout('email')
        ->disableLayout();
    $layout->content = $this->_view->render($template);
    $html = $layout->render();
    
    $this->setBodyHtml($html, $this->getCharSet(), $encoding)->send();
    

    The call to Zend_Layout::disableLayout() prevents direct output of the layout rendering and allows you instead to store the rendered layout in the $html variable. Then, you have to manually store the rendering of the Zend_View template in into the Zend_Layout::content variable. After that, you're set.

    You can also use Zend_Layout::setView to set an instance of Zend_View within the layout so that when you render the layout, you can get access to view variables. You could probably also write a view helper to take care of this.