Phoenix.Swoosh.render_body
render_body
, go back to Phoenix.Swoosh module for more information.
Renders the given template
and assigns
based on the email
.
Once the template is rendered the resulting string is stored on the email
fields html_body
and text_body
depending on the format of the template.
.html
, .htm
, and .xml
are stored in html_body
; all other extensions,
(e.g. .txt
and .text
), in text_body
.
Arguments
email
- theSwoosh.Email
struct.template
- may be an atom or a string. If an atom, like:welcome
, it will render both the HTML and text template and stores them respectively on the email. If the template is a string it must contain the extension too, likewelcome.html
.assigns
- a dictionnary with the assigns to be used in the view. Those assigns are merged and have higher order precedence than the email assigns. (email.assigns
)
Examples
defmodule Sample.UserEmail do
use Phoenix.Swoosh, view: Sample.EmailView
def welcome(user) do
%Email{}
|> from("tony@stark.com")
|> to(user.email)
|> subject("Hello, Avengers!")
|> render_body("welcome.html", %{username: user.email})
end
end
The example above renders a template welcome.html
from Sample.EmailView
and
stores the resulting string onto the html_body field of the email.
(email.html_body
)
In many cases you may want to set both the html and text body of an email. To do so you can pass the template name as an atom (without the extension):
def welcome(user) do
%Email{}
|> from("tony@stark.com")
|> to(user.email)
|> subject("Hello, Avengers!")
|> render_body(:welcome, %{username: user.email})
end
Layouts
Templates are often rendered inside layouts. If you wish to do so you will have
to specify which layout you want to use when using the Phoenix.Swoosh
module.
defmodule Sample.UserEmail do
use Phoenix.Swoosh, view: Sample.EmailView, layout: {Sample.LayoutView, :email}
def welcome(user) do
%Email{}
|> from("tony@stark.com")
|> to(user.email)
|> subject("Hello, Avengers!")
|> render_body("welcome.html", %{username: user.email})
end
end
The example above will render the welcome.html
template inside an
email.html
template specified in Sample.LayoutView
. put_layout/2
can be
used to change the layout, similar to how put_view/2
can be used to change
the view.