How to use underscore.js as a template engine ? - GeeksforGeeks

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.
Approach:
Writing the template: A template contains simple HTML with some embedded logical segments. Logical segments can be added in the following three ways:<% executable javascript code %><%= value to be printed %><%- HTML escaped value to be printed %>
<% executable javascript code %><%= value to be printed %><%- HTML escaped value to be printed %>
<% executable javascript code %>
<%= value to be printed %>
<%- 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.
_.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:<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>
<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.<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>
<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:
JavaScript - Underscore.js
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?