Client side Templating using Underscore.js and JQuery

Recently, I ran into requirement where I was getting JSON response and needed to render it on my Mobile application. I had two Options, Server side processing and Client side Templating. I studied and checked both way ; came to conclusion on using Client side Templating. There are many plugins and libraries available however there is one which stands different, easy to use and faster as compared to others which is “Underscore.js“.

Underscore.js library needs JQuery as prerequisite. You can find complete documentation here, Only remember following three points :

  1. <% %> – to execute some code
  2. <%= %> – to print some value in template
  3. <%- %> – to print some values with HTML escaped

Example Source code:

Below Example shows how to render JSON in tabular format using Underscore.js and JQuery.

		Demo of Templating using underscore.js

<style type="text/css">
.outer {
    border-collapse: collapse;
    font: 12px/16px arial, sans-serif;
    margin: 20px;
    padding: 0;

.outer td, .outer th {
    border: solid 1px #ddd;
    margin: 0;
    padding: 5px;

.outer th, .outer {
    background: #EEE;
    font-weight: bold;



<table class="outer">
            <th>Sr. No</th>

<script type="text/html" id='table-data'>
    <% _.each(items,function(item,key,list){ %>
            <td><%= key+1 %></td>
            <td><%= %></td>
    <% }) %>


	<script type="text/JavaScript"


	<script type="text/JavaScript"

src="" ></script>

	<script type="text/JavaScript" >
	var items = [
		{name:"Client Side Templating"}

	var tableTemplate = $("#table-data").html();

	$("table.outer tbody").html(_.template( tableTemplate,{items:items} ));






How it Works ?

  1. Line 31, we are going to append data in this table.
  2. Line 42-48, defines template on how we are going to render JSON values. We are looping through values and rendering in “td” tag of “table”.
  3. Line 73, Single line is doing the magic here. It is getting template which is defined between line 42 and 48 and then rendering values in table defined at line 31.

Please leave comment for feedback.





Related Posts


4 responses to “Client side Templating using Underscore.js and JQuery”

  1. aaa Avatar


  2. Avatar

    It’s very good. thank U so much

  3. Kirti Mishra Avatar
    Kirti Mishra

    Hi. I tried using this in my dev org. Doesn’t seem to work 🙁

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Jitendra Zaa

Subscribe now to keep reading and get access to the full archive.

Continue Reading