Yii Framework Forum: SwiftMailer and Layouts - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

SwiftMailer and Layouts Adding layouts to the setBody renderer

#1 User is offline   daxiang28 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 1
  • Joined: 06-July 12

Posted 06 July 2012 - 04:08 PM


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';	

main.php config:
Add the layoutPath to the mail config
			'layoutPath' => 'application.views.layouts.mail',


#2 User is offline   mikewalen 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 41
  • Joined: 27-August 11
  • Location:Hamilton, New Zealand

Posted 19 November 2012 - 08:09 PM

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

Many thanks :)

Share this topic:

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users