Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

How to use underscore.js as a template engine ?

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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 mentioned 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.

Below example illustrates the above approach: Example: Consider the template string specified below:

  • Code 1: 

javascript




<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>

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

javascript




<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>

  • Output:

My Personal Notes arrow_drop_up
Last Updated : 21 Dec, 2022
Like Article
Save Article
Similar Reads
Related Tutorials