yii-mail extension using layout


(Gustavo) #1

If you use the extension yii-mail and want to use layouts do the following

Open YiiMailMessage file

add a public property called $layout




public $layout;



change the setBody method to




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

{

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

  if (!is_array($body)) 

   $body = array('body'=>$body);

  if(isset(Yii::app()->controller))

   $controller = Yii::app()->controller;

  else

   $controller = new CController('YiiMail');

			

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

  $body = $controller->renderInternal($viewPath, array_merge($body, array('mail'=>$this)), true);

  if($this->layout!==null)

  {

   $layout=$controller->getLayoutFile($this->layout);

   $body=$controller->renderInternal($layout,array('content'=>$body),true);

  }

 }

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

}



now use it like this




$message=new YiiMailMessage;

...

$message->layout='//mail/layout';

//points to the views folder / mail / layout.php 

//or

$message->layout='test'; 

//will point to the layouts folder / test.php



[size="3"]note:[/size] it will use the same approach a controller does to render a layout

so you can use paths like ‘test’ that will point to the alias application.views.layouts.test

or ‘//mail/test’ that will point the the alias application.views.mail.test

the same applies for the view, you can set your views like you do in when rendering a view, like //test/myView

attached is the modified file

Hope this helps


(Johnnyma1988) #2

Actually, i think yii-mail already provides a solution to let us use the layout of email.

You could use the property of $view like below:




$message->view='test'; //this would be pointed to protected/views/mail/test.php

$message->setBody('Message content here with HTML', 'text/html');



If so, we could implement it without changing it :)

Really hopes it would be helpful to you, thx.


(Mahashmi) #3

Thanks for this, greatly helps. I have models that trigger emails going out and the layout and views are working quite well. However, I am curious how I can embed images in the layout (as opposed to remotely linking them). For this I would need an instance of the $message in the layout itself.

Any idea how I can go about this?

Thanks.


(Calvin Ent) #4

Hi Mustafa. I’m facing the same problem here. Have you found the sollution yet ? Thanks


(Javierleal) #5

I think this would be a way to approach that:

http://swiftmailer.org/docs/messages.html#embedding-inline-media-files