The Underscore.js library is well known for its useful JavaScript functional programming helpers and utility methods. One of those utility methods is _.template()
. This method is used to compile strings with expressions into functions that replace those expressions with dynamic values.
Underscore.js template syntax delimiters resemble those of the ERB, or Embedded Ruby template syntax, with an equals sign following the opening tag:
<p>Hello, <%= name %>.</p>
An Underscore.js template expression used within HTML looks like the preceding example. The variable name would be dynamically passed in to the compiled function for this template.
The _.template()
method can also be used to parse and execute arbitrary JavaScript code within a template. JavaScript code within Underscore.js templates is delimited by using the ERB style tags without an equals sign following the opening tag:
<ul> <% _.each(items, function(item) { %> ...