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 Rate Topic: -----

#1 User is offline   daxiang28 

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

Posted 06 July 2012 - 04:08 PM

Hi,

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.

Thanks,
Steve




A couple modifications to the extension files:

YiiMailMessage.php
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
			if(file_exists($viewPath)){
				$body = $controller->renderInternal(
					Yii::getPathOfAlias(Yii::app()->mail->viewPath.'.'.$this->view).'.php', 
					array_merge($bodyParams, array('mail'=>$this)), 
					true
				);	
	
				$layoutPath = Yii::getPathOfAlias(Yii::app()->mail->layoutPath.'.'.$this->layout).'.php';
				if(file_exists($layoutPath)){
					$body = $controller->renderInternal(
						$layoutPath, 
						array_merge($bodyParams, array('content'=>$body)), 
						true
					);	
				}
			}			
		}
		return $this->message->setBody($body, $contentType, $charset);
	}	



YiiMail.php
add to class:
public $layoutPath = 'application.views.layouts.mail';	


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

1

#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 :)
0

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