In order to feel comfortable in week3, you have to pass the exam from week2.
We are going to use lodash as a standard library from now on!
Bookmark the documentation since we are going to use it a lot!
From now on, we are going to use different template engines to create HTML from our JavaScript.
This means that we are going to stop concatenating HTML strings in our code!
For starters, we are going to use _.template from lodash.
The funciton takes 3 arguments:
textwith text and template placeholdersdata- an object where eachkeyrepresent placeholders intext. Those keys are replaced by the givenvalueoptions- optional argument for giving options to the template
A basic usage is:
var p = "<p><%= name %></p>";
var pHtml = _.template(p, {
name: "Ivan"
});
console.log(pHtml); // <p>Ivan</p>We can also do for-loops in the template by using the _(arr).forEach from lodash:
var
items = ["Edno", "Dve", "Tri"],
template = "<ul><% _(items).forEach(function(item) { %><li><%= item %></li><% }); %></ul>",
parsedHtml = _.template(template, {
items: items
});
console.log(parsedHtml); // "<ul><li>Edno</li><li>Dve</li><li>Tri</li></ul>"The important thing here to notice is the difference between <% and <%= in the template.
If we want more from our templates - like a for cycle that is not hardcoded in string or custom template handlers, we will a better template engine thatn _.tempate
One of the many out there is called Handlerbars.js
You can install Handlebars with Bower:
bower install handlebars --save
The documentation on the website is a godo start: http://handlebarsjs.com/