简体   繁体   中英

The best approach to store email templates in Yii

I am now implementing a functionality which allows sending system emails to users registered in my Yii 1.1 project.

I am a beginner developer so I still need a hint sometime, so I have a couple of simple questions about the implementation of storing and retrieving email template files which will be used when sending system messages (using swiftMailer, for example).

  1. Which folder of the Yii application is best suited for storing HTML email templates for system messages?
  2. Which class should my "Email Template" model extend since the email templates will be stored as files and the model won't interact with the database.
  3. Is the approach (separate "Email Template" model + storing email template files on the system) a good one for this kind of thing?

If anyone can recommend doing things differently, that will also be much appreciated.

Emails aren't different than other types of views, only that their delivery mechanism is different. Here's where Yii expects your templates to be:

yii/
-- protected/
   -- views/
      -- mail/
         -- template.html

You can specify templates from within Yii for your emails. See the documentation for YiiMailMessage->setBody :

/**
* Set the body of this entity, either as a string, or array of view 
* variables if a view is set, or as an instance of 
* {@link Swift_OutputByteStream}.
* 
* @param mixed the body of the message.  If a $this->view is set and this 
* is a string, this is passed to the view as $body.  If $this->view is set 
* and this is an array, the array values are passed to the view like in the 
* controller render() method
* @param string content type optional. For html, set to 'html/text'
* @param string charset optional
*/

Example:

$message = new YiiMailMessage;
$message->view = 'main_tpl';
$message->setBody(array(
    'data' => $data,
    'user' => $user,
));
$message->subject = $subject;
$message->addTo($email);
$message->from = $from;
Yii::app()->mail->send($message);

This prepares a message with the yii/protected/views/mail/main_tpl.php template, and sends it along with $data and $user to fill up the missing pieces.

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