back to Overview

_.template()

Parses a Handlebars-like template to create a reusable template function.
Util module only.

Syntax Variants

_.template(template)
_.template(template, escapeFunction)

Parameters

template
The template as a string using the syntax described below.
escapeFunction (optional)
The callback function(inputString) that will be used to escape all output:
inputString
The string to escape.
(callback return value)
The escaped string.
If no escapeFunction has been given, the output will not be escaped. _.escapeHtml() can be used as an escape function for HTML, and _.escapeRegExp() for regular expressions. JavaScript's built-in escape() function can escape URL components.
(return value)
the value returned by the last invocation of func

Description

Parses a Handlebars-like template to create a reusable template function.

The syntax of the template uses a syntax that superficially looks like Handlebars. Unlike Handlebars, it is based on raw JavaScript expressions and thus gives you complete freedom, but also offers you shortcuts for formatting, iteration and conditionals.

Every template can receive exactly one object as input. If you need more than one value as input, put all required values into an object.

Use double curly braces to embed a JavaScript expression and insert its result:

{{a}} plus {{b}} is {{a+b}}

To use such a template, create it with template() and then execute the resulting function:

var myTemplate = _.template('{{a}} plus {{b}} is {{a+b}}');
var result = myTemplate({a: 5, b: 7});
If you pass an object as input, its properties will be mapped using JavaScript's with statement and are available as variables throughout the template.

If you have only a simple value to render, you can pass it directly and access it through the pre-defined variable obj:

var myTemplate = _.template('The result is {{obj}}.');
var result = myTemplate(17);
Alternatively, you could also access the input as this, but be aware that JavaScript wraps simples types such as Number and Boolean. this is the default, so you can omit it to get the same result:
var myTemplate = _.template('The result is {{ }}.');
var result = myTemplate(17);

Minified templates can use _.formatValue() formats directly. Just separate them from the expression by a double-colon:

The price is {{obj::#.00}}.

Conditions can be expressed using if and else:

Hello {{if visits==0}}New{{else if visits<10}}Returning{{else}}Regular{{/if}} Customer.
You can use any JavaScript expression as condition.

Use each to iterate through a list:

var myTemplate = _.template(
	   '{{each names}}{{this.firstName}} {{this.lastName}}{{/each}}');
var result = myTemplate({names: [{firstName: 'Joe', lastName: 'Jones'},
                                 {firstName: 'Marc', lastName: 'Meyer'}]});
each will iterate through the members of the given object. It calls its body for each item and put a reference to the item into this. Optionally, you can specify up to two variables to store the value in and the zero-based index of the current item:
var myTemplate = _.template(
	   '{{each value, index: names}}{{index}}. {{value.firstName}} {{value.lastName}}{{/each}}');

If you do not pass an expression to each, it will take the list from this:

var myTemplate = _.template('{{each value:}}{{value}};{{/each}}');
var result = myTemplate([1, 2, 3]);

Beside lists, you can also iterate through the properties of an object. The property name will be stored in the first given parameter and the value in this and the second parameter:

var myTemplate = _.template('{{each key, value: nicknames}}{{key}}: {{value}}{{/each}}');
var result = myTemplate({nicknames: {Matt: 'Matthew', John: 'Jonathan'} });

Shorter version of the previous example that uses this for the value:

var myTemplate = _.template('{{each key: nicknames}}{{key}}: {{this}}{{/each}}');

If you do not need the key, you can omit the variable specification:

var myTemplate = _.template('{{each nicknames}}{{this}}{{/each}}');

You can define your own variables, using the regular JavaScript syntax, with 'var':

var myTemplate = _.template('{{var s=very.long.name, sum=a+b;}}{{s.desc}}, {{sum}}');

In some situations, it may be inevitable to embed raw JavaScript in the template. To embed JavaScript code, prefix the code with a '#':

var myTemplate = _.template(
    '{{each}}{{#var sum = 0; for (var i = 0; i < 3; i++) sum += this.numbers[i]; }}{{sum}}{{/each}}');
var result = myTemplate([['Foreword', 'Intro'], ['Something', 'Something else']]);

By default, all output will be escaped. You can prevent this by using triple-curly-braces:

Here's the original: {{{rawText}}}
.

The template's JavaScript code is executed in a sandbox without access to global variables. Minified defines the following variables for you:

NameDesciption
thisThe template object outside of each. Inside eachs, the current value.
objThe parameter given to the template function.
_A reference to Minified Util.
escThe escape function given when the template has been defined. If no function has been given, a default function that returns the input unmodified.
printA function(text,...) that appends one or more strings to the template result.
eachA function(listOrObject, eachCallback) that can iterate over lists or object properties. The eachCallback is a function(key, value) for objects or function(value, index) for arrays that will be invoked for each item.

Every template you create is already cached, so it not an expensive operation to call _.template() a second time with the same template. However, because of caching, you should be careful when creating templates dynamically, as this will fill the cache up quickly.

See also..

  • _.format() shares template()'s syntax but returns the result directly.
  • _.formatHtml() is a variant of format() with HTML escaping.
  • _.escapeHtml() can be used by template() to escape HTML.
  • _.escapeRegExp() can be used by template() to escape regular expressions.
  • HTML() creates a HTML element tree from a template.

Comments

comments powered by Disqus

back to Overview

Functions