Phoenix apps use Braces in two ways:
- Templates in your code.
.hbs,.mustache,.liquid,.jinja,.django,.njk,.twig,.tera,.hubl,.mailchimpand.mustachiofiles that render like.heexfiles, from controllers, components andPhoenix.Template. They are compiled with your app, so a mistake fails the build. - Templates in your data. Templates your users write, such as email templates kept in the
database, rendered at runtime and previewed in a LiveView. This guide's examples are
Handlebars; a template in another language converts to Handlebars with
Braces.convert/2, or renders with its own module'srender/3.
The integration is defined only when its optional dependencies are installed. A Phoenix app
already has them: phoenix_template for .hbs templates (Braces.Handlebars.Phoenix.Engine),
phoenix_live_view for Braces.HTML and Braces.Handlebars.HTML, and phoenix_html for Braces.Handlebars.safe/1 as safe
HTML.
# mix.exs
def deps do
[
{:braces, "~> 0.1"},
# ...
]
end.hbs templates
Register the engine in config/config.exs:
config :phoenix_template, :template_engines, hbs: Braces.Handlebars.Phoenix.EngineThen .hbs files work wherever .heex files do. A Phoenix 1.7+ controller renders the
templates its view module embeds:
# lib/my_app_web/controllers/page_html.ex
defmodule MyAppWeb.PageHTML do
use MyAppWeb, :html
embed_templates "page_html/*"
end{{! lib/my_app_web/controllers/page_html/home.html.hbs }}
<h1>Hi {{first_name}}</h1>
<ul>
{{#each items}}<li>{{name}}</li>{{else}}<li>Nothing yet</li>{{/each}}
</ul># lib/my_app_web/controllers/page_controller.ex
def home(conn, _params) do
render(conn, :home, first_name: "Ada", items: [%{name: "Tea & cake"}])
endThe template is rendered inside your app's layouts as a .heex template would be.
- Assigns are the data.
{{first_name}}reads@first_name. Structs work too:{{user.name}}reads thenamefield of@user. - Components. In a
Phoenix.Componentmodule,home/1is a function component:<MyAppWeb.PageHTML.home first_name="Ada" items={[]} />. - Escaping. Values are escaped once, as Handlebars.js escapes them; Phoenix doesn't escape
the result again. Phoenix's safe values, such as
Phoenix.HTML.raw/1's, andBraces.Handlebars.safe/1values aren't escaped. - Formats. A file needs its format, as in Phoenix:
home.hbsfails compilation, since Phoenix can't tell whether to escape it. Name ithome.html.hbs. In formats that aren't HTML, such ashome.text.hbs, values are written as they are, as Phoenix writes them in.text.eex. - Strict. A missing value raises a
Braces.Handlebars.RenderError, as a missing assign does in HEEx.
Templates in other languages
Each language has its own engine. Register the ones you use:
config :phoenix_template, :template_engines,
hbs: Braces.Handlebars.Phoenix.Engine,
mustache: Braces.Mustache.Phoenix.Engine,
jinja: Braces.Jinja.Phoenix.Engine,
django: Braces.Django.Phoenix.Engine,
njk: Braces.Nunjucks.Phoenix.Engine,
twig: Braces.Twig.Phoenix.Engine,
tera: Braces.Tera.Phoenix.Engine,
liquid: Braces.Liquid.Phoenix.Engine,
hubl: Braces.HubL.Phoenix.Engine,
mailchimp: Braces.Mailchimp.Phoenix.Engine,
mustachio: Braces.Mustachio.Phoenix.Enginewelcome.html.jinja, welcome.html.liquid and the others then work as welcome.html.hbs
does: compiled with your module, so a template that doesn't parse fails the build at its
line, escaped in HTML formats, and written as it is in others. Each renders as its module's
render/3 does, with its own language's rules: a missing value renders nothing.
To compile a template inside a module instead of from a file, use its language's sigil,
such as ~JINJA (import Braces.Jinja, only: :sigils), and render it with
Braces.render/3.
One template in several formats
home.html.hbs and home.text.hbs both become home/1, so embed each format with its own
pattern and suffix, as with any Phoenix template:
defmodule MyAppWeb.Notifications do
import Phoenix.Template, only: [embed_templates: 2]
embed_templates "notifications/*.html", suffix: "_html"
embed_templates "notifications/*.text", suffix: "_text"
end
MyAppWeb.Notifications.home_html(assigns)
MyAppWeb.Notifications.home_text(assigns)
Phoenix.Template.render_to_string(MyAppWeb.Notifications, "home_text", "text", assigns)Compile errors
The file is compiled into Elixir code with your module, as Braces.Handlebars.embed_templates/2
compiles it (see Compiled templates), so a template that doesn't
parse, or that can't render whatever its data, fails the build at its line:
** (CompileError) lib/my_app_web/controllers/page_html/home.html.hbs:2: Handlebars template error: if doesn't match unless - 2:3
{{#if member}}
^Helpers and partials
The engine has no custom helpers or partials, so {{> footer}}, or a helper that isn't built
in, fails compilation. For templates that need them, use a module that uses Braces.Handlebars,
which compiles its helpers and partials with its templates:
defmodule MyAppWeb.Receipts do
use Braces.Handlebars, helpers: MyAppWeb.ReceiptHelpers, partials: "receipts/partials/*.hbs"
embed_templates "receipts/*.hbs"
endIts functions return iodata, which HEEx would escape again. Mark it as safe HTML where you render it:
<section>{Phoenix.HTML.raw(MyAppWeb.Receipts.summary(%{order: @order}))}</section>Keep that module apart from your Phoenix.Component modules: both import an
embed_templates macro, and they clash.
Templates in your data
Templates that your users write are parsed at runtime. Braces.Handlebars.render/3 reads them
without generating code or creating atoms, so they can't run code or exhaust the atom table.
Validating on save
Reject a template that doesn't parse when it's saved, with the error's description. An HTML
template is also rejected when it can write a value without escaping, which
Braces.Handlebars.unescaped_outputs/2 finds (see Security):
defmodule MyApp.Notifications.Template do
use Ecto.Schema
import Ecto.Changeset
schema "notification_templates" do
field :subject, :string
field :body, :string
timestamps()
end
def changeset(template, attrs) do
template
|> cast(attrs, [:subject, :body])
|> validate_required([:subject, :body])
# The subject is text, rendered with no_escape: true, so it may write values as they are.
|> validate_handlebars(:subject, html: false)
|> validate_handlebars(:body, html: true)
end
defp validate_handlebars(changeset, field, html: html?) do
validate_change(changeset, field, fn field, source ->
with {:ok, template} <- Braces.Handlebars.compile(source),
[] <- if(html?, do: Braces.Handlebars.unescaped_outputs(template), else: []) do
[]
else
{:error, error} ->
[{field, error.description}]
[found | _rest] ->
[{field, "#{found.description}, on line #{found.line}"}]
end
end)
end
end{{#if a}} gives body: "Parse error on line 1, column 9: unexpected \"\"", and {{{bio}}}
gives body: "\"bio\" is written without escaping, on line 1". A template that
parses can still fail to render with some data, for example in strict mode, so handle
{:error, %Braces.Handlebars.RenderError{}} where you render it.
Previewing in a LiveView
Braces.Handlebars.HTML.render/1 is a function component that renders a template in HEEx, as safe
HTML. Give it the source as the user types, and it shows the error instead of crashing the
LiveView:
defmodule MyAppWeb.TemplateEditorLive do
use MyAppWeb, :live_view
def mount(_params, _session, socket) do
sample = %{"first_name" => "Ada", "items" => [%{"name" => "Tea & cake"}]}
{:ok, assign(socket, body: "<p>Hi {{first_name}}</p>", sample: sample)}
end
def render(assigns) do
~H"""
<form phx-change="change">
<textarea name="body" phx-debounce="300">{@body}</textarea>
</form>
<Braces.Handlebars.HTML.render template={@body} data={@sample}>
<:error :let={error}><pre class="error">{error.message}</pre></:error>
</Braces.Handlebars.HTML.render>
"""
end
def handle_event("change", %{"body" => body}, socket) do
{:noreply, assign(socket, body: body)}
end
endtemplateis Handlebars source, parsed on each render, or a template fromBraces.Handlebars.compile/2or~HBS, parsed once.- The
:errorslot gets theBraces.Handlebars.ParseErrororBraces.Handlebars.RenderError. Itsmessagehas the line and a caret under the error. Without the slot, the error is raised. strictmakes a missing value an error, to catch a misspelled variable in the preview.
Braces.HTML.render/1 does the same for a template in any language. Give the language of
source, and the options of its render/3 as opts:
<Braces.HTML.render template={@body} language={:liquid} data={@sample} opts={[templates: @partials]}>
<:error :let={error}><pre class="error">{Exception.message(error)}</pre></:error>
</Braces.HTML.render>Rendering in HEEx
Braces.Handlebars.render!/3 returns iodata, which HEEx would escape again. In HEEx, render with
Braces.Handlebars.HTML.render!/3, which returns safe HTML, {:safe, iodata}, or, for a
template in any language, Braces.HTML.render!/3:
<div>{Braces.Handlebars.HTML.render!(@template, @data, helpers: MyAppWeb.ReceiptHelpers)}</div>
<div>{Braces.HTML.render!(@liquid_template, @data)}</div>Braces.Handlebars.safe/1 values are safe HTML to Phoenix too, so a helper that returns one can be
rendered in HEEx as it is.
Escaping user-written templates
Values are escaped in {{value}}, but a template's author can write them as they are: with
{{{value}}} or {{&value}}, and with a block helper, whose result isn't escaped, as
{{#lookup . "bio"}}{{/lookup}}. Reject those when the template is saved (see
Validating on save).
The template's own text is HTML too: its author can write a <script>. When the person who
writes a template isn't trusted with your page, render it where its HTML can't do harm, such as
a sandboxed <iframe srcdoc>, or sanitize the result. See Security.
Testing
Function components render with Phoenix.LiveViewTest.rendered_to_string/1, and templates
with Phoenix.Template.render_to_string/4:
test "home greets the user" do
html = Phoenix.Template.render_to_string(MyAppWeb.PageHTML, "home", "html",
first_name: "<Ada>", items: [])
assert html =~ "Hi <Ada>"
end