Braces.Handlebars.Sigil (Braces v0.1.0)

Copy Markdown View Source

The ~HBS sigil: a Handlebars template compiled with your code, as HEEx compiles ~H. It gives a Braces.Handlebars.Template whose render function was generated from the template, so Braces.Handlebars.render/3 runs that code instead of reading the AST, and a path such as {{user.name}} looks up :user and :name in atom-keyed data without converting strings to atoms. It renders exactly as a template from Braces.Handlebars.compile/2 does.

iex> import Braces.Handlebars.Sigil
iex> template = ~HBS"Hi {{first_name}}!"
iex> to_string(template)
"Hi {{first_name}}!"
iex> Braces.Handlebars.render_to_string(template, %{first_name: "Ana"})
{:ok, "Hi Ana!"}

In a module that uses Braces.Handlebars, the template calls the helpers and partials that use Braces.Handlebars gives (see Braces.Handlebars.__using__/1); elsewhere it has none. A template that doesn't parse, or that can't render whatever its data, such as {{#if}} without its argument, a decorator, or a helper or partial that isn't defined, raises a CompileError at its line in your file. The message gives the line and column in the template, then the template's line with a caret under the error:

# lib/my_app/email.ex, line 3
~HBS"""
{{#if member}}
  Welcome back
{{/unless}}
"""
# ** (CompileError) lib/my_app/email.ex:4: Handlebars template error: if doesn't match unless - 1:3
#
#     {{#if member}}
#        ^

In a module, each template's code is a hidden function of the module, named after a hash of that code, so the template can be kept in a module attribute. While the module compiles, before that function exists, such as in @preview Braces.Handlebars.render!(@template, data), Braces.Handlebars.render/3 reads the template's AST instead. An earlier version of the module that is still loaded, as after IEx's r/1, only has that function for the same template. Outside a module, such as in IEx, the code is an anonymous function.

Summary

Functions

sigil_HBS(arg, modifiers)

(macro)