简体   繁体   中英

Accessing the CakeEmail subject from a template/layout

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!

除了将主题设置为视图变量之外,没有其他方法。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM