Shravan Kumar Kasagoni

Skip Navigation

How to Use UnderscoreJS Templates

 /  Leave a response

I am using Underscore.js from long time, it’s a JavaScript library that provides useful functional programming helpers without extending any built-in objects. I recently came across it’s templating capabilities. Underscore provides _.template() function to dynamically build markup from a template and some data(JavaScript objects).

Here is the syntax:  _.template(templateString, [settings])

_.template() compiles JavaScript templates into functions that can be evaluated for rendering complicated bits of HTML from JSON data sources.

We can use following three types of code blocks in templates:

  • <%= … %>
    • Evaluate an expression and render the result inline
  • <%- … %>
    • Evaluate an expression and render the html escaped result inline
  • <% … %>
    • Execute arbitrary code

Here is an example, there is a person object with name property, I want render it on the page using underscore template.

To make this example work add UnderscoreJS library to html page, then add following div and javascript.

<div id='output'></div>

window.onload = function() {
	var person = {
	    name: 'Shravan Kumar'
	};

	var templateString = 'Name: <%= name %>';

	var template = _.template(templateString);

	var result = template(person);

	var outputDiv = document.querySelector('#output');

	outputDiv.innerHTML = result;
};

Find source code @ jsfiddle

In above code snippet we did the following:

  1. Prepare data object which you want to use in template.
  2. Prepare template using _.template() with templateString using any of the valid code blocks in place the of placeholders where you want render properties in data object. This step will return a compiled template function.
  3. Pass the data object as parameter to compiled template function of previous step output and render the final output of this step on page.

Instead of using inline templates they can be stored inside script tags with a non-JavaScript ‘type’ attribute, here is an example:


<div id='output'></div>

<script id='sample-template' type='text/html'>
  <p>
    Latitude: <%= latitude %>
  </p>
  <p>
    Longitude: <%= longitude %>
  </p>

  <% var numbers = [1, 2, 3, 4, 5]; %>
  <ul>
    <% _(numbers).each(function(number) { %>
      <li>
        <%= number %>
      </li>
      <% }); %>
  </ul>

  <p>
    HTML escaped output: <%-htmlContent%>
  </p>
</script>


window.onload = function() {

  var data = {
    latitude: 20.2,
    longitude: 30.5,
    htmlContent: '<div class="title">This <span>UnderscoreJs Templating</span> Example</div>'
  };

  var templateSelector = document.querySelector('#sample-template');

  var templateString = templateSelector.innerHTML;

  var template = _.template(templateString);

  var result = template(data);

  var outputDiv = document.querySelector('#output');

  outputDiv.innerHTML = result;

};

To make above example work add UnderscoreJS library to html page, then add div, template script tag and javascript.

Find source code @ jsfiddle

Find more info on _.template() function @ UnderscoreJS site.

Write a response

Your email address will not be published. Required fields are marked *

All code will be displayed literally.