Braces.Handlebars.Helpers (Braces v0.1.0)

Copy Markdown View Source

Custom helpers for Braces.Handlebars.render/3, written as Elixir functions.

A helper takes the template's arguments in order, then a Braces.Handlebars.Helpers.Options, as a Handlebars.js helper does. Define helpers as the public functions of a module that uses Braces.Handlebars.Helpers, or as anonymous functions in a map, and pass them as helpers::

defmodule MyApp.EmailHelpers do
  use Braces.Handlebars.Helpers

  def shout(text, _options), do: String.upcase(text)

  def link(url, options) do
    Braces.Handlebars.safe(~s(<a href="#{Braces.Handlebars.escape(url)}">#{options.fn.(options.this)}</a>))
  end
end

Braces.Handlebars.render(template, data, helpers: MyApp.EmailHelpers)
Braces.Handlebars.render(template, data, helpers: %{"shout" => fn text, _options -> String.upcase(text) end})

helpers: takes a module, a map of names to functions, or a list of them; later ones win. A helper with three arguments in the template is called with four: the three and the options. A module can define a helper for several numbers of arguments.

What a helper returns is written as a value: escaped in {{helper}} unless it's made with Braces.Handlebars.safe/1, and written as it is by a block helper ({{#helper}}…{{/helper}}), whose options.fn gives text that's already escaped.

Custom helpers take the place of built-in ones of the same name. A helperMissing helper is called, with the name in options.name, for a helper that isn't defined and a value that's missing, and blockHelperMissing for a block named after a value, as in Handlebars.js.

Summary

Functions

Renders a block helper's block with context, as options.fn.(context) does, with more @ variables or block params, as Handlebars.js's options.fn(context, {data, blockParams}).

Renders a block helper's {{else}} block, as render_block/3 renders the block.

Functions

render_block(options, context, opts \\ [])

Renders a block helper's block with context, as options.fn.(context) does, with more @ variables or block params, as Handlebars.js's options.fn(context, {data, blockParams}).

  • data: %{"index" => 0} adds @index on top of the block's @ variables;
  • block_params: [item, index] gives the values of as |item index|.

A helper that repeats its block, with @n and as |n|:

iex> helpers = %{
...>   "times" => fn count, options ->
...>     Enum.map_join(1..count, fn n ->
...>       Braces.Handlebars.Helpers.render_block(options, options.this, data: %{"n" => n}, block_params: [n])
...>     end)
...>   end
...> }
iex> template = Braces.Handlebars.compile!("{{#times 3 as |n|}}{{@n}}{{n}} {{/times}}")
iex> Braces.Handlebars.render_to_string(template, %{}, helpers: helpers)
{:ok, "11 22 33 "}

render_inverse(options, context, opts \\ [])

Renders a block helper's {{else}} block, as render_block/3 renders the block.