There are many types of template engines in the foreground, and I personally feel that handlebars is more portable.
First, GitHub downloads a newer version of Handelbars.js http://handlebarsjs.com
After downloading it, we need to introduce JS to the page.
1 < script type = "Text/javascript" src = "Script/jquery.js" ></ script > 2 < Script type = "Text/javascript" Span style= "COLOR: #ff0000" > src = "Script/handlebars-1.0.0.beta.6.js" Span style= "COLOR: #0000ff" >></ script >
After the introduction of the
We need to define the data placeholder in HTML in handlebars the most basic is to use {{}} Package for example {{value}} Handlebars module will automatically match the corresponding value, object or function
1 < div class = "Demo" > 2 < h1 > {{Name}}</ h1 > 3 < p > {Content}} </ p > 4 </ div >
You can also create a template separately, with ID or class to determine uniqueness, type is fixed indispensable
1 <ScriptID= "TPL"type= "Text/x-handlebars-template">2 <Div class="Demo">3 <H1>{{title}}</h1>4 <P>{{Content.title}}</p>5 </div>6 </Script>
Use Handlebars.compile () in JS to precompile the template
1 //Use jquery to get templates 2 var TPL = $ ("#tpl"). html (); 3 var template = Handlebars.compile (TPL); 4 //Analog JSON data 5 var context = {name: "Zhaoshuai", Content: "Learn Handlebars"}; 6 //Match JSON content 7 var html = template (context);
Generally we use the template engine is the most important to solve the data traversal problem so handlebars has built-in expressions each we can use {{#each name}} to traverse the contents of a list block, using this to refer to the traversed element, name is an array
1 < ul > 2 {{#each name}}3 < Li > {{This}} </ Li > 4 {{/each}}5</ul>
The corresponding JSON is:
1 {2 name: ["HTML", "CSS", "JavaScript"]3 };
After compiling:
1 <ul>2 <Li>Javascript</Li>3 <Li>Html</Li>4 <Li>Css</Li>5 </ul>
In the end must be mentioned is the introduction of the time must be placed in the back of jquery or handlebars inside some methods will be error
Make a little more comments in the template
The wording is as follows:
1 {{! Handlebars comments}}
Finally, put a good code on it.
Handlebars.js template engine with