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:
- <% 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 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:
Please Login to comment...