SwiftMailer and Layouts


New to Yii and just wanted to post a solution I had for a question I saw a while back for incorporating layouts in the jonah’s mail extension. I wanted to template my emails in a similar fashion to how Yii uses layouts and views for web rendering. Just wanted to post if this helps someone out or if anybody has a better idea how to accomplish.



A couple modifications to the extension files:


Add to class:

public $layout = 'main';	

(override the setBody function)

	public function setBody($body = '', $contentType = null, $charset = null) {

		if ($this->view !== null) {

			$bodyParams = (!is_array($body)) ? array('body'=>$body) : $body;


			// if Yii::app()->controller doesn't exist create a dummy 

			// controller to render the view (needed in the console app)

			$controller = (isset(Yii::app()->controller)) ? Yii::app()->controller : new CController('YiiMail');


			// renderPartial won't work with CConsoleApplication, so use 

			// renderInternal - this requires that we use an actual path to the 

			// view rather than the usual alias

			$viewPath = Yii::getPathOfAlias(Yii::app()->mail->viewPath.'.'.$this->view).'.php';

			// If view file does not exist, then it's an empty string


				$body = $controller->renderInternal(


					array_merge($bodyParams, array('mail'=>$this)), 




				$layoutPath = Yii::getPathOfAlias(Yii::app()->mail->layoutPath.'.'.$this->layout).'.php';


					$body = $controller->renderInternal(


						array_merge($bodyParams, array('content'=>$body)), 






		return $this->message->setBody($body, $contentType, $charset);



add to class:

public $layoutPath = 'application.views.layouts.mail';	

[size="2"]main.php config:[/size]

Add the layoutPath to the mail config

			'layoutPath' => 'application.views.layouts.mail',

This is great daxiang28. Just what I was after :)

Many thanks :)