Before the project encountered in the DOM to add a lot of HTML structure, silly in the JS to write a bunch of templates, and then replace with one to do the replacement. At that time is ugly point, do not feel what, now understand the template engine after looking back to really catch the urgent, later is not so silly.
Today to introduce a personal think more useful template engine, underscore in the template method, I think underscore this library is really good, there are plans to watch the source side of the analysis of learning, then will summarize some experience it.
_.template(templateString, [data], [settings])
This is the API for the template method, which accepts three parameters, where:
The first parameter is also the necessary parameter is the template string, you can insert the variable through the <%=%>, you can also insert the JS code through the <%%>, you can also use <%-%> to do HTML escape, if the variables are many, can be used <% Print ()%> to simplify.
The second parameter is the data passed into the template, if the second argument is not passed, then this method will return a template function, the template function can be worn into the data to return the completed template, if the incoming data parameter will directly return a completed template.
The third parameter is the setting, such as this method by default is looking for <%%> to replace, you can set it to change the specific method can be referenced here
The usage is actually very simple
var cmpiled = _.template ("Hello <%= name%>"// "Hello Mike"
It can be noted that the template can be inserted into the JS code, then for a very long with fairly repetitive content, you can do this processing
<Scripttype= "Text/template" id= "TPL"> <%_.each (data,function(n) {%> <P>Name:<%=N.name%>, Age:<%=N.age%>, Gender:<%=N.sex%></p> <% }); %></Script>
var data = [ { ' Mike ', ' m '}, { ' Nina ', +, ' woman ' }, { ' elle ', ' female ' }]; $ (' body '). Append (_.template ($ (' #tpl '). HTML (), data));
In this way, in the JS code can only be used for data processing, without appearing that a string of smelly and long template string, greatly improve the code readability, but also in a sense to achieve the separation of data and performance.
Using-template method for underscore template engine