4. String Templates

If you want to generate strings from a template, _.template([string=''], [options={}]) is a simple yet powerful function to do that. It can be used by libraries and applications to avoid long string concatenations. Grunt uses _.template to support templates in configuration files. It can also be used in applications to generate HTML markups, messages, emails and more.

Listing 10.1 Basic usage of string templates
let tpl = _.template('Hello, <%= name %>. Current time is <%= new Date() %>.'\
);
tpl({
  name: 'Alex'
});
// -> 'Hello, Alex. Current time is Fri Jun 23 2017 20:07:19 GMT+1200 (NZST).'

In Listing 10.1, the input argument of _.template is the template itself. In the template, <%= and %> are the delimiters to wrap variables to be evaluated at runtime. _.template returns a new function. After invoking the returned function with a context object that contains actual values of template variables, it returns the generated string. If no value is assigned to a variable, an empty string will be used.

_.template supports three types of delimiters, interpolate, escape and evaluate.

4.1 interpolate

interpolate delimiters allow to interpolate variables. The default regular expression pattern to declare interpolated variables is /<%=([\s\S]+?)%>/g. Simple variables and complex expressions are both supported. The regular expression pattern of interpolate delimiters can be customized by the property interpolate of the options object.

Listing 10.2 Use interpolate delimiters
let tpl = _.template('Hello, <%= name %>, the total amount is <%= order.amoun\
t + 10 %>.');
tpl({
  name: 'Alex',
  order: {
    amount: 100,
  }
});
// -> 'Hello, Alex, the total amount is 110.'

4.2 escape

It’s common to use _.template to generate HTML markups. escape delimiters allow to interpolate variables and escape the result values. The default regular expression pattern to declare escaped variables is /<%-([\s\S]+?)%>/g. The pattern can be customized by the property escape of the options object.

Listing 10.3 Use escape delimiters
let tpl = _.template('<div><%- markup %></div>');
tpl({
  markup: '<span>Hello</span>'
});
// -> '<div>&lt;span&gt;Hello&lt;/span&gt;</div>'

4.3 evaluate

evaluate delimiters allow executions of JavaScript code. This kind of delimiters is useful when adding logic to templates, e.g. adding condition checks or loops to the template. The default regular expression pattern to declare JavaScript code is /<%([\s\S]+?)%>/g. The pattern can be customized by the property evaluate of the options object.

Listing 10.4 Use evaluate delimiters
let tpl = _.template('<% if (a > 0) { %> Good! <% } else { %> Bad! <% } %>');
tpl({
  a: 1
});
// -> ' Good! '
tpl({
  a: -1
});
// -> ' Bad! '

4.4 imports

Besides from the context object passed to the function created by _.template, a default object can also be passed to _.template as an additional source when evaluating variables. The object is specified using the property imports of the options object. The default values in the imported object can be overridden by values in the context object.

Listing 10.5 Use extra imports
let tpl = _.template('Hi, <%= user %>, you should pay <%= amount * discount %\
>.',
  {
    imports: {
      discount: 0.8,
  }
});
tpl({
  user: 'Alex',
  amount: 100
});
// -> 'Hi, Alex, you should pay 80.'
tpl({
  user: 'Bob',
  amount: 100,
  discount: 0.9
});
// -> 'Hi, Bob, you should pay 90.'

The default imports object contains only the lodash object itself with the key _, so lodash methods can be used directly in the expressions.

4.5 Data object name

By default, when evaluating variables in the template, variables use the same names as in the context object. The property variable of the options object sets a name to the context object, then variable names should be changed accordingly.

Listing 10.6 Use different variable object name
var tpl = _.template('Hello, <%= user.name %>.', {
  variable: 'user',
});
tpl({
  name: 'Alex'
});
// -> 'Hello, Alex.'

In Listing 10.6, the context object’s name is set to user, so user.name accesses the property name of the context object.