Braces.Handlebars (Braces v0.1.0)

Copy Markdown View Source

Handlebars templates in Elixir, rendered as Handlebars.js 4.7.10 renders them.

iex> template = Braces.Handlebars.compile!("Hi {{name}}!")
iex> Braces.Handlebars.render_to_string(template, %{name: "Ada & Co"})
{:ok, "Hi Ada & Co!"}

For Phoenix and Swoosh, see the Phoenix and Swoosh guides.

Summary

Rendering

Parses a template for render/3: a Braces.Handlebars.Template with its source and AST. Takes the options of parse/2. A ~HBS template (Braces.Handlebars.Sigil) is the same struct, parsed and compiled into Elixir code when your module compiles.

Like compile/2, raising Braces.Handlebars.ParseError when the template doesn't parse.

Decodes JSON for render/3, keeping each object's keys in the order they're written, which Elixir maps don't keep. An object is a list of {key, value} tuples, which render/3 reads as an object, so #each walks it as Handlebars.js does. A key written twice keeps its first place and its last value, as JSON.parse does. An empty object is %{}, since [] is an empty array. Errors are those of JSON.decode/1.

Renders a template with data, as Handlebars.js 4.7.10 renders it, to iodata.

Like render/3, raising Braces.Handlebars.RenderError when the template can't be rendered.

Compiled templates

Imports embed_templates/2 and the ~HBS sigil (Braces.Handlebars.Sigil), and gives the module's templates their helpers and partials.

Compiles each Handlebars file that matches pattern into a function of your module, named after the file up to its first dot: emails/welcome.hbs becomes welcome(data, opts \\ []), which renders it to iodata as render!/3 does, running code compiled from the template as ~HBS does, so what can't be rendered raises a Braces.Handlebars.RenderError. It renders in strict mode unless you pass strict: false: a missing value is an error. It takes the other options of render/3 too. This is the signature of the functions Phoenix's embed_templates defines. Call it after use Braces.Handlebars.

The ~HBS sigil, described in Braces.Handlebars.Sigil. Import it with import Braces.Handlebars, only: :sigils; use Braces.Handlebars imports it too.

Escaping

HTML-escapes a value as {{value}} does, giving a string: for helpers that build HTML. Text made with safe/1 isn't escaped.

Marks text as safe, so render/3 writes it without escaping, even in {{value}}.

Finds where a template can write a value without HTML escaping, for templates that people you don't fully trust write, such as email templates your users edit. Returns a list, in the template's order, with each place's kind, name, description, line (from 1) and column (from 0). An empty list means every value the template writes is escaped, unless a helper returns safe/1 text.

Parsing

Parses a Handlebars template into its AST, after whitespace control.

Like parse/2, raising Braces.Handlebars.ParseError when the template doesn't parse.

Parses a Handlebars template into its AST with no whitespace control: each Braces.Handlebars.AST.ContentStatement's value is the text as written.

Prints an AST as Handlebars source.

Lists the data a template reads, as paths from the data's root, sorted: what a form or a sample needs to fill in, or a check that data has before it's sent.

Liquid

Converts a Handlebars AST, as parse/2 gives it, to a Liquid template that renders as Handlebars.js renders the Handlebars, by way of Braces.IR: variables, paths, #if, #unless, #each and #with with {{else}}, @index, @first, @last and @key in #each, partials and layouts, and the Braces.Filters helpers that Liquid has filters for, such as upper, add and eq. Anything else, such as other helpers or {{^…}}, is a Braces.ConversionError with its line and column. Braces.convert/2 converts to Liquid from the other languages.

Like to_liquid/1, raising Braces.ConversionError when the template can't be converted.

Converting

Writes a Braces.IR as Handlebars source, with the Braces.Filters helpers for what Handlebars has no syntax for, or gives a Braces.ConversionError for what Handlebars can't say, such as variables.

Reads Handlebars, its source or its AST, into a Braces.IR, for Braces.convert/2. {{name}} is a value; give helpers:, the names of the helpers your template calls without arguments, for {{helper}} to be a call.

Rendering

compile(source, opts \\ [])

Parses a template for render/3: a Braces.Handlebars.Template with its source and AST. Takes the options of parse/2. A ~HBS template (Braces.Handlebars.Sigil) is the same struct, parsed and compiled into Elixir code when your module compiles.

iex> {:ok, template} = Braces.Handlebars.compile("Hi {{name}}")
iex> Braces.Handlebars.render_to_string(template, %{"name" => "Ana"})
{:ok, "Hi Ana"}

compile!(source, opts \\ [])

Like compile/2, raising Braces.Handlebars.ParseError when the template doesn't parse.

decode_json(json)

Decodes JSON for render/3, keeping each object's keys in the order they're written, which Elixir maps don't keep. An object is a list of {key, value} tuples, which render/3 reads as an object, so #each walks it as Handlebars.js does. A key written twice keeps its first place and its last value, as JSON.parse does. An empty object is %{}, since [] is an empty array. Errors are those of JSON.decode/1.

iex> Braces.Handlebars.decode_json(~s({"b": 1, "a": {"c": [true, null]}, "e": {}, "b": 2}))
{:ok, [{"b", 2}, {"a", [{"c", [true, nil]}]}, {"e", %{}}]}

iex> Braces.Handlebars.decode_json(~s({"a": 1}x))
{:error, {:invalid_byte, 8, ?x}}

render(template, data, opts \\ [])

Renders a template with data, as Handlebars.js 4.7.10 renders it, to iodata.

Takes a Braces.Handlebars.Template, from compile/2 or ~HBS, or an AST from parse/2. A template from compile/2, or an AST, is read as it renders: nothing is compiled to code and no atoms are created. A ~HBS template runs the code compiled from it, which renders the same.

Values are looked up and written as Handlebars.js does:

  • a path looks up each key in maps, then in struct fields; a key is tried as a string first, then as an atom that already exists, so decoded JSON and atom-keyed maps both work. Lists have length and indexes (items.[0]), and strings have length;
  • a list of {key, value} tuples with string keys, as decode_json/1 gives, is an object whose keys keep their order;
  • false, nil, "", 0 and [] are false in #if and #unless (includeZero=true counts 0 as true), and all but 0 are empty in #with;
  • numbers, true and false are written as JavaScript writes them, lists as their elements joined with commas, and maps and objects as [object Object]. Structs that implement String.Chars, such as Date, are written with it;
  • {{value}} escapes &<>"' ` and = as Handlebars.js does. {{{value}}}, {{&value}} and values made with safe/1, or {:safe, iodata} tuples, aren't escaped.

The built-in helpers are those of Handlebars.js: if, unless, each, with, lookup and log (to Logger), with {{else}} and {{else if}}. #each over an object walks keys that are array indexes in numeric order, as JavaScript does, then the others in the list's order, or sorted in a map, since Elixir maps don't keep the order keys were added in. Helpers and partials that aren't given, and decorators other than {{#*inline}}, are RenderErrors.

Options:

  • strict: true makes a missing value an error, as Handlebars.js's strict option does;
  • no_escape: true writes {{value}} without escaping;
  • data: %{...} adds @ variables, as Handlebars.js's data runtime option does;
  • helpers: adds helpers: a module that uses Braces.Handlebars.Helpers, a map of names to functions, or a list of them (see Braces.Handlebars.Helpers);
  • partials: %{name => partial} adds partials, each a Braces.Handlebars.Template from ~HBS or compile/2, so it's checked before it renders. An AST or source text is taken too, but source is only parsed when a render calls it. {{#*inline}} partials take the place of these in their block.

A ~HBS template takes its helpers and partials from its module's use Braces.Handlebars instead, and raises ArgumentError when given helpers: or partials:.

iex> template = Braces.Handlebars.compile!("{{> greeting}} {{shout name}}")
iex> Braces.Handlebars.render_to_string(template, %{"name" => "ada"},
...>   partials: %{"greeting" => Braces.Handlebars.compile!("Hi")},
...>   helpers: %{"shout" => fn text, _options -> String.upcase(text) end}
...> )
{:ok, "Hi ADA"}

Returns {:error, %Braces.Handlebars.RenderError{}} with the line and column of what failed.

iex> template = Braces.Handlebars.compile!("{{#each items}}<li>{{name}}</li>{{else}}None{{/each}}")
iex> {:ok, iodata} = Braces.Handlebars.render(template, %{"items" => [%{"name" => "Tea & cake"}]})
iex> IO.iodata_to_binary(iodata)
"<li>Tea &amp; cake</li>"

iex> {:error, error} = Braces.Handlebars.render(Braces.Handlebars.compile!("Hi {{name}}"), %{}, strict: true)
iex> error.message
~s("name" not defined in data - 1:5\n\n    Hi {{name}}\n         ^)

render!(template, data, opts \\ [])

Like render/3, raising Braces.Handlebars.RenderError when the template can't be rendered.

render_to_string(template, data, opts \\ [])

Like render/3, giving a string.

Compiled templates

__using__(opts)

(macro)

Imports embed_templates/2 and the ~HBS sigil (Braces.Handlebars.Sigil), and gives the module's templates their helpers and partials.

defmodule MyApp.Emails do
  use Braces.Handlebars, helpers: MyApp.EmailHelpers, partials: "emails/partials/*.hbs"

  embed_templates "emails/*.hbs"
end
  • helpers: a module that uses Braces.Handlebars.Helpers, or a list of them; later ones win.
  • partials: a wildcard (Path.wildcard/1) of partial files, relative to the directory of the module's file. Each is a partial named after its file up to the first dot: emails/partials/footer.hbs is {{> footer}}. Each is compiled into the module, as embed_templates compiles templates, and is an @external_resource.

The module's embed_templates and ~HBS templates render with these helpers and partials, and only these: render/3 raises ArgumentError when given helpers: or partials: for them. So a template that calls a helper that isn't one of them, or one of them with a number of arguments it can't take, or a partial by a name that isn't one of them nor one of its {{#*inline}} partials, is a CompileError. A partial file may call a partial by the name of an {{#*inline}} partial that a template of the module defines, as a layout does with the partials that templates define in its partial block. {{> (name)}}, whose name is only known as it renders, is a RenderError when there's no such partial, and so is helperMissing or blockHelperMissing in place of a missing helper, as in Handlebars.js.

embed_templates(pattern, opts \\ [])

(macro)

Compiles each Handlebars file that matches pattern into a function of your module, named after the file up to its first dot: emails/welcome.hbs becomes welcome(data, opts \\ []), which renders it to iodata as render!/3 does, running code compiled from the template as ~HBS does, so what can't be rendered raises a Braces.Handlebars.RenderError. It renders in strict mode unless you pass strict: false: a missing value is an error. It takes the other options of render/3 too. This is the signature of the functions Phoenix's embed_templates defines. Call it after use Braces.Handlebars.

pattern is a wildcard (Path.wildcard/1) relative to the directory of the module's file, or to :root, itself relative to that directory. Each file is an @external_resource, so editing one recompiles the module, as does adding or removing a file that matches the pattern.

A file that doesn't parse, or that can't render whatever its data, raises a CompileError at its line in the file, with the line and a caret under the error.

sigil_HBS(source, modifiers)

(macro)

The ~HBS sigil, described in Braces.Handlebars.Sigil. Import it with import Braces.Handlebars, only: :sigils; use Braces.Handlebars imports it too.

Escaping

escape(value)

HTML-escapes a value as {{value}} does, giving a string: for helpers that build HTML. Text made with safe/1 isn't escaped.

iex> Braces.Handlebars.escape(~s(<a href="?q=1&r=2">))
"&lt;a href&#x3D;&quot;?q&#x3D;1&amp;r&#x3D;2&quot;&gt;"

safe(iodata)

Marks text as safe, so render/3 writes it without escaping, even in {{value}}.

iex> template = Braces.Handlebars.compile!("{{link}}")
iex> Braces.Handlebars.render_to_string(template, %{link: Braces.Handlebars.safe(~s(<a href="/">Home</a>))})
{:ok, ~s(<a href="/">Home</a>)}

unescaped_outputs(template, opts \\ [])

Finds where a template can write a value without HTML escaping, for templates that people you don't fully trust write, such as email templates your users edit. Returns a list, in the template's order, with each place's kind, name, description, line (from 1) and column (from 0). An empty list means every value the template writes is escaped, unless a helper returns safe/1 text.

  • kind: :unescaped: {{{value}}} and {{&value}}, for a value or a helper's result. Text written in the template, such as {{{"<br>"}}}, isn't listed.
  • kind: :block_helper: a block helper's result is written without escaping, as in Handlebars.js, so {{#lookup . "bio"}}{{/lookup}} writes bio as it is, and so do {{{{lookup . "bio"}}}}{{{{/lookup}}}} and your own block helpers. #if, #unless, #each, #with and #log only render their blocks, and aren't listed.

Pass the helpers you render with as helpers:, as render/3 takes them, so their block calls, {{{helper}}}, and a custom helperMissing or blockHelperMissing are listed. Partials aren't followed: check the ones people write on their own.

The template's own text is HTML too, so a template that writes no unescaped value can still have a <script>. Render templates you don't trust where their HTML can't do harm, such as an <iframe sandbox>, or sanitize the result.

iex> template = Braces.Handlebars.compile!(~s(Hi {{name}}\n{{{bio}}} {{#lookup . "bio"}}{{/lookup}}))
iex> for found <- Braces.Handlebars.unescaped_outputs(template),
...>     do: {found.kind, found.name, found.line, found.column}
[{:unescaped, "bio", 2, 0}, {:block_helper, "lookup", 2, 10}]

iex> Braces.Handlebars.unescaped_outputs(Braces.Handlebars.compile!("{{#if a}}{{b}}{{/if}}"))
[]

Parsing

parse(source, opts \\ [])

Parses a Handlebars template into its AST, after whitespace control.

Pass ignore_standalone: true to keep the lines around block, comment and partial tags alone on their line, as Handlebars.js's ignoreStandalone does.

iex> {:ok, ast} = Braces.Handlebars.parse("Hi {{name}}")
iex> [%Braces.Handlebars.AST.ContentStatement{value: "Hi "}, %Braces.Handlebars.AST.MustacheStatement{}] = ast.body

iex> {:error, error} = Braces.Handlebars.parse("{{#if a}}{{/each}}")
iex> error.description
"if doesn't match each - 1:3"
iex> error.message
"if doesn't match each - 1:3\n\n    {{#if a}}{{/each}}\n       ^"

parse!(source, opts \\ [])

Like parse/2, raising Braces.Handlebars.ParseError when the template doesn't parse.

parse_without_processing(source)

Parses a Handlebars template into its AST with no whitespace control: each Braces.Handlebars.AST.ContentStatement's value is the text as written.

to_string(program)

Prints an AST as Handlebars source.

The text is printed as it is in the AST, so print what parse_without_processing/1 gives, or an AST you built: printing what parse/2 gives and parsing the result would apply whitespace control twice. Raises ArgumentError for an AST that no source parses to, such as text ending in { right before a tag.

iex> Braces.Handlebars.to_string(Braces.Handlebars.parse!("{{#if a}}{{b}}{{else}}\{{c}}{{/if}}"))
"{{#if a}}{{b}}{{else}}\{{c}}{{/if}}"

variables(template, opts \\ [])

Lists the data a template reads, as paths from the data's root, sorted: what a form or a sample needs to fill in, or a check that data has before it's sent.

iex> template = Braces.Handlebars.compile!("""
...> Hi {{user.first_name}}!
...> {{#each items as |item|}}{{item.name}}: {{money item.price}} {{@index}}{{/each}}
...> {{#with company}}{{name}}, {{../user.email}}{{/with}}
...> """)
iex> Braces.Handlebars.variables(template, helpers: %{"money" => fn cents, _ -> cents end})
["company.name", "items[].name", "items[].price", "user.email", "user.first_name"]

A path's segments are joined with dots, and [] stands for each element of a list: items[].name is the name of each of items. Segments with dots or spaces are written in brackets, [first name]. Only the deepest paths are listed, since user.name implies user.

Paths are followed as Handlebars resolves them: in #each and #with, through block params, ../ and @root. @index and the other @ variables, literals, and the names of helpers aren't data, and aren't listed: pass your helpers as helpers:, as render/3 takes them, so {{shout}} isn't read as a value. A helper's arguments are listed.

  • partials: the partials to follow, as render/3 takes them, so the paths they read are listed, in the context they're called with. {{#*inline}} partials are followed too.

Some paths can't be known before rendering: what a custom block helper renders its block with, a {{> (dynamic)}} partial, and lookup with a key from the data. Their blocks are read in the context they're in. In a section, {{#items}}{{name}}{{/items}}, names are listed under the section's value, items.name, though for a list Handlebars reads each element.

Liquid

to_liquid(program)

Converts a Handlebars AST, as parse/2 gives it, to a Liquid template that renders as Handlebars.js renders the Handlebars, by way of Braces.IR: variables, paths, #if, #unless, #each and #with with {{else}}, @index, @first, @last and @key in #each, partials and layouts, and the Braces.Filters helpers that Liquid has filters for, such as upper, add and eq. Anything else, such as other helpers or {{^…}}, is a Braces.ConversionError with its line and column. Braces.convert/2 converts to Liquid from the other languages.

Values are written as JavaScript writes them, and HTML-escaped as Handlebars escapes them. The data has to be what JSON gives, with lists for #each. See the Handlebars to Liquid guide for the few values that render differently.

iex> {:ok, liquid} = Braces.Handlebars.to_liquid(Braces.Handlebars.parse!("{{#each items}}{{@index}}: {{{name}}} {{/each}}"))
iex> liquid
~s({% for item in items %}{{ forloop.index0 | join: "," | escape | replace: "&#34;", "&quot;" | replace: "&#39;", "&#x27;" | replace: "`", "&#x60;" | replace: "=", "&#x3D;" }}: {{ item.name | join: "," }} {% endfor %})

iex> Braces.Handlebars.to_liquid(Braces.Handlebars.parse!("Hi {{> footer}}"))
{:ok, ~s(Hi {% include "footer" %})}

iex> {:error, error} = Braces.Handlebars.to_liquid(Braces.Handlebars.parse!("Hi\n{{> footer this}}"))
iex> error.message
"A partial with a context or arguments, or a dynamic name, isn't supported on line 2, column 0"

to_liquid!(program)

Like to_liquid/1, raising Braces.ConversionError when the template can't be converted.

Converting

from_ir(ir, opts \\ [])

Writes a Braces.IR as Handlebars source, with the Braces.Filters helpers for what Handlebars has no syntax for, or gives a Braces.ConversionError for what Handlebars can't say, such as variables.

to_ir(source_or_ast, opts \\ [])

Reads Handlebars, its source or its AST, into a Braces.IR, for Braces.convert/2. {{name}} is a value; give helpers:, the names of the helpers your template calls without arguments, for {{helper}} to be a call.