引入:html
代碼寫在body下的script標籤裏面,而且id="template",type的類型爲type="text/x-handlebars-template"後端
記得還要去js中去配置一些東東:less
算了吧,來一篇直接粘貼過去就能拿來用的,之後一號拿來複習再鞏固spa
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>handlebars</title> <style> .big { width: 100px; height: 100px; border: 1px solid green; border-radius: 100px; position: relative; } .small { width: 50px; height: 50px; border: 1px solid green; border-radius: 50px; position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; text-align: center; line-height: 50px; } </style> </head> <body> <div id="container"></div> <script id="template" type="text/x-handlebars-template"> <h1>Hello</h1> <h2>Handlebars</h2> <table border="1"> <thead> <tr> <th>姓名</th> <th>年齡</th> <th>性別</th> </tr> </thead> <tbody> <tr> <td>{{name}}</td> <td>{{age}}</td> <td>{{gender}}</td> </tr> </tbody> </table> <p>hello, {{name}}</p> <p>{{hello}}</p> <table border="1"> <thead> <tr> <th>姓名</th> <th>年齡</th> <th>性別</th> </tr> </thead> <tbody> {{#each listOfStudents}} <tr> <td>{{name}}</td> <td>{{age}}</td> <td>{{gender}}</td> </tr> {{/each}} </tbody> </table> <p>hello, {{{person.a.name}}}</p> <p>hello, {{person/a/name}}</p> <div class="big"> <div class="small"> 2 </div> </div> <div class="big"> <div class="small"> 3 </div> </div> <div class="big"> <div class="small"> 4 </div> </div> <!-- {{circle name}} {{circle name}} {{circle name}} --> </script> <script src="./handlebars-v4.0.5.js"></script> <script> // 獲取模板的源代碼 var source = document.getElementById('template').innerHTML; // 把模板的源代碼,編譯成模板對象 var template = Handlebars.compile(source); // 建立helper Handlebars.registerHelper('circle', function(data ) { // 告訴系統,這個返回值要解析成真正的標籤 var obj = new Handlebars.SafeString('<div class="big"><div class="small">' + data + '</div></div>'); return obj; }); // 經過模板對象,獲取最終html代碼 var html = template({ person: { a: { name: 'Tom<input type="text">' }, b: 'hello' }, name: 'Bob', age: 20, listOfStudents: [ { name: 'bob', age: 20, gender: 'male' }, { name: 'tom', age: 22, gender: 'male' }] }); // console.log(html); // 把html代碼插入到網頁中去 document.getElementById('container').innerHTML = html; // helper </script> </body> </html>