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 :
- <% %> – to execute some code
- <%= %> – to print some value in template
- <%- %> – 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.
How it Works ?
- Line 31, we are going to append data in this table.
- 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”.
- 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.