Introduction
Basics of the template engine
We are using the Underscore template engine. Everything you need to know about the template engine is here.
But only need to keep in mind three simple template things (three kinds of annotations):
<% %>
- to execute some Javascript code;<%= %>
- to print some value in template;<%- %>
- to print some values with HTML escaped.
A Simple example
All templates are based on two things: JSON object (data) and template (html with template annotations). Inside the template annotations it's possible to access object properties like normal Javascript variables. Take a look at the case below.
JSON object:
{
"title": "Blade Runner",
"year": 1982,
"tags": ["Sci-Fi", "Thriller"]
}
Template (HTML with annotations):
<h1>Movie: <%- title%> (<%- year%>)</h2>
<ul>
<% _.each(tags, function(tagName){ %>
<li><%- tagName%></li>
<% }); %>
</ul>
Note: _.each is an Underscore function to iterate over a list.
Result:
<h1>Movie: Blade Runner (1982)</h2>
<ul>
<li>Sci-Fi</li>
<li>Thriller</li>
</ul>
List properties
If you have a template and don't know the JSON Object, try to log the object inside the template to your browser's developer tools console. To do this follow the next steps:
Add this line
<% console.log("JSON Object:", arguments[0]); %>
to the template;<% console.log("JSON Object:", arguments[0]); %> <h1>Movie: <%- title%> (<%- year%>)</h2> <ul> <% _.each(tags, function(tag){ %> <li><%- tag%></li> <% }); %> </ul>
Now open the developer tools and refresh the page;
In the console tab it is possible to see the JSON Object;