Handlebars - The easy stuffs

handlebars

In what context can a helper be accessed?

Handlebars helpers can be accessed from any context in a template.

How does Handlebars allow for name conflict resolution between helpers and data fields?

Handlebars also allows for name conflict resolution between helpers and data fields via a this reference:

<p>{{./name}} or {{this/name}} or {{this.name}}</p>

Any of the above would cause the name field on the current context to be used rather than a helper of the same name.

If your helper returns HTML that you do not want escaped, what should you do?

If your helper returns HTML that you do not want escaped, make sure to return a new Handlebars.SafeString.

Handlebars.registerHelper('agree_button', function() {
  var emotion = Handlebars.escapeExpression(this.emotion),
      name = Handlebars.escapeExpression(this.name);

  return new Handlebars.SafeString(
    "<button>I agree. I " + emotion + " " + name + "</button>"
  );
});

How can we comment out a block of template?

Use {{!-- --}} or {{! }}.

<div class="entry">
  {{!-- only output this author names if an author exists --}}
  {{#if author}}
    <h1>{{firstName}} {{lastName}}</h1>
  {{/if}}
</div>

The comments will not be in the resulting output. If you'd like the comments to show up. Just use html comments, and they will be output.

<div class="entry">
  {{! This comment will not be in the output }}
  <!-- This comment will be in the output -->
</div>

Any comments that must contain }} or other handlebars tokens should use the {{!-- --}} syntax.

Handlebars comments are not visible in the HTML but if you want to show them, you can use the standard HTML comment: <!comments>.

How can we prevent handlebars from doing HTML escaping?

Handlebars HTML-escapes values returned by a {{expression}}. If you don't want Handlebars to escape a value, use the "triple-stash", {{{.

Handlebars will not escape a Handlebars.SafeString. If you write a helper that generates its own HTML, you will usually want to return a new Handlebars.SafeString(result). In such a circumstance, you will want to manually escape parameters.

Handlebars.registerHelper('link', function(text, url) {
    text = Handlebars.Utils.escapeExpression(text);
    url  = Handlebars.Utils.escapeExpression(url);

    var result = '<a href="' + url + '">' + text + '</a>';

    return new Handlebars.SafeString(result);
});

This will escape the passed in parameters, but mark the response as safe, so Handlebars will not try to escape it even if the "triple-stash" is not used.

How can we register multiple helpers in one shot?

A helper is a function. The below code register a helper named 'foo', and another helper named 'bar'.

Handlebars.registerHelper({
  foo: function() {
  },
  bar: function() {
  }
});

How can we register multiple partials in one shot?

A partial is just a string (it is a template string). The below code register multiple partials:

Handlebars.registerPartial({
  foo: '...',
  bar: '...'
});

If loading the whole library, then the partials may be string values which will be compiled on demand. If only loading the runtime, then we must replace '…' with the precompiled partial that has been properly setup using the Handlebars.template method.

How can we specify different behaviors or configuration options for Handlebars?

See Handlebars.compile from http://handlebarsjs.com/reference.html

**What is the purpose of Handlebars.SafeString?*

Prevents string from being escaped when the template is rendered.

new Handlebars.SafeString('<div>HTML Content!</div>')

When constructing the string that will be marked as safe, any external content should be properly escaped using the Handlebars.escapeExpression method to avoid potential security concerns.

What is the purpose of Handlebars.escapeExpression?

HTML escapes the passed string, making it safe for rendering as text within HTML content.

Handlebars.Utils.escapeExpression(string)

Replaces &, <, >, ", ', `, = with the HTML entity equivalent value for string values. SafeString values are left untouched.

The output of all expressions except for triple braced expressions are passed through this method. Additionally helpers should use this method when returning HTML content via a SafeString instance to prevent possible code injection.

This method is aliased at Handlebars.Utils.escapeExpression.

What is the purpose of Handlebars.log(level, message)?

Logger utilized by the log helper. May be overriden if desired.

What is the purpose of Handlebars.Utils.isEmpty(value)?

Determines if a given value is empty.

Handlebars.Utils.isEmpty(value)

This is used by the native if and with helpers control their execution flow. Handlebar's definition of empty is any of:

  • Array with length 0
  • falsy values other than 0

Which is intended to match the Mustache behavior

What is the purpose of Handlebars.Utils.extend(obj, value)?

imple utility method to augment obj with all keys defined on value.

Handlebars.Utils.extend(foo, {bar: true})

Will set the key bar on object foo with the value true.

This is a utility method. Perhaps we can use it for stuff that is not related to Handlebars, instead of writing our own extend method.

What is the purpose of Handlebars.Utils.toString(obj)?

This is a generic toString method. Perhaps we can use it to serialize an object.

What is the purpose of Handlebars.Utils.isArray(obj)?

Determines if an obj is an array.

What is the purpose of Handlebars.Utils.isFunction(obj)?

Determines if an obj is a function.

What is the purpose of Handlebars.Utils.appendContextPath(contextPath, id)?

Takes a given contextPath value and generates the path to the child, id.

Handlebars.Utils.appendContextPath('foo.bar', 'baz')

Will return foo.bar.baz.

What is the purpose of @root?

Initial context that the template was executed with.

{{#each array}}
  {{@root.foo}}
{{/each}}

Unless explicitly modified this value is consistent across all portions of the page rendering, meaning it's be be used within partials where depthed parameters are unable to reference their parent template.

What is the purpose of @first?

Set to true by the each helper for the first step of iteration.

{{#each array}}
  {{#if @first}}
    First!
  {{/if}}
{{/each}}

What is the purpose of @index?

Zero-based index for the current iteration step. Set by the each helper.

{{#each array}}
  {{@index}}
{{/each}}

What is the purpose of @key?

Key name for the current iteration step. Set by the each helper when iterating over objects.

{{#each obj}}
  {{@key}}
{{/each}}

**What is the purpose of @last?**

> Set to true by the each helper for the last step of iteration.

[[code]]
{{#each array}}
  {{#if @last}}
    Last :(
  {{/if}}
{{/each}}
[[/code]]

**What is the purpose of the @log variable?**

> Assigned log level. 

[[code]]
template({}, {data: {level: Handlebars.logger.WARN}})

May be set to one of Handlebars.logger.DEBUG , Handlebars.logger.INFO , Handlebars.logger.WARN , or Handlebars.logger.ERROR

When set the logger will only output when the Handlebars.logger.level value is set to that value or more verbose. This value defaults to logging only error mode.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License