Skip to content
Related Articles

Related Articles

How to use underscore.js as a template engine ?
  • Last Updated : 02 Mar, 2020

While writing layouts for web pages, it is often the case that we require certain elements of the page to have dynamic values. For such scenarios, we use templates. Templates enable us to embed logical segments inside static HTML code, which makes the page dynamic based on the values passed in the template. To render templates, we require a template engine. In this article, we will discuss how the popular JavaScript library underscore.js can be used as a template engine.


  • Writing the template: A template contains simple HTML with some embedded logical segments. Logical segments can be added in the following three ways:
    1. <% executable javascript code %>
    2. <%= value to be printed %>
    3. <%- HTML escaped value to be printed %>
  • Rendering the template using underscore.js: Underscore.js provides .template() function which compiles JavaScript templates into functions that can be evaluated for rendering.
    _.template(templateString, settings)

    Parameters: The _.template function accepts two parameters as mentionedd above and described below:

    • templateString: A string containing the template that is to be rendered.
    • settings(optional): A hash containing any _.templateSettings that should be overwritten.

    Return values: The _.template function returns a function with the variables specified in the template as its parameters. The function can be called with desired parameter values to obtain dynamic HTML.

Below example illustrates the above approach:

Example: Consider the template string specified below:

  • Code 1:

    var templateString = '<div id="output">
        My name is
        <%= name %>
    <p> I can print numbers using templates </p>
    <% var numbers = [1, 2, 3, 4, 5]; %>
        <% _(numbers).each(function(number) { %>
                <%= number %>
        <% }); %>
    <p>And HTML escaped output as well
  • Code 2: Here’s how this template can be rendered using underscore.js.

    <div id="output"></div>
        window.onload = function() {
            var outputDiv = document.querySelector('#output');
            // Obtain the template rendering function
            // from template string
            var templateFunction = _.template(templateString);
            // Render the template with specified parameters
            outputDiv.innerHTML = templateFunction({
                "name": "John",
                "htmlEscaapedOutput":"<div class="title">"+
                "This <span>is HTML escaped output</span> example</div>"
  • Output:


My Personal Notes arrow_drop_up
Recommended Articles
Page :