How to use underscore.js as a template engine ?

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.

Approach:

  • 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.
    Syntax:

    _.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:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <script>
    var templateString = '<div id="output">
    <p>
        My name is
        <%= name %>
    </p>
        
    <p> I can print numbers using templates </p>
      
    <% var numbers = [1, 2, 3, 4, 5]; %>
    <ul>
        <% _(numbers).each(function(number) { %>
            <li>
                <%= number %>
            </li>
        <% }); %>
    </ul>
      
    <p>And HTML escaped output as well
        <%=htmlEscapedOutput%>
    </p>';
    </script>

    chevron_right

    
    

  • Code 2: Here’s how this template can be rendered using underscore.js.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <div id="output"></div>
      
    <script>
        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>"
            });
        }
    </script>

    chevron_right

    
    

  • Output:

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.