0

I'm using CakeEmail as follows:

$Email = new CakeEmail();
$Email->template('my_template', 'my_layout');
$Email->subject('My Subject');
// ...

How do I access the 'My Subject' value in my_layout.ctp?

The closest thing I could find was this but it's not very relevant. I'm looking at the CakeEmail::_renderTemplates() source code and it doesn't seem to do that but I'm not sure.

I know I can also pass the subject line to $Email->viewVars but that's not very flexible. Please advise!

Community
  • 1
  • 1
ᴍᴇʜᴏᴠ
  • 4,804
  • 4
  • 44
  • 57
  • An option I didn't think about when I asked the question: create your own wrapper around `CakeEmail` with all the necessary functionality. – ᴍᴇʜᴏᴠ May 15 '16 at 00:54

2 Answers2

3

There's no other way besides setting the subject to a view var too.

ADmad
  • 8,102
  • 16
  • 18
  • 2
    Upvoted. Just make the subject a variable and use it with the subject and as template var. The other answer works as well, but do you seriously want all that code plus overloading a class just to archive *that*? – floriank Jan 18 '16 at 21:14
3

Other than setting a View variable there is no way of doing this with CakeEmail. However, you could extend CakeEmail so that the email's subject is added to the available variables in your template.

I haven't tested this, but you should be able to do something like this:-

// app/Lib/CustomCakeEmail.php

App::uses('CakeEmail', 'Network/Email');

class CustomCakeEmail extends CakeEmail {

    protected function _renderTemplates($content) {
        if (!empty($this->_subject) && empty($this->_viewVars['subject'])) {
            $this->_viewVars['subject'] = $this->_subject;
        }
        return parent::_renderTemplates($content);
    }

}

Here CakeEmail::_renderTemplates() is extended to set the subject in the view variables (as long as it hasn't already been set elsewhere). You'd then use the extended class instead of CakeEmail like this:-

App::uses('CustomEmail', 'Lib');

$Email = new CustomCakeEmail();
$Email->template('my_template', 'my_layout');
$Email->subject('My Subject');

Your View template would have a $subject variable containing the email's subject.

drmonkeyninja
  • 8,490
  • 4
  • 31
  • 59