表达式
1 <div class="entry"> <h1>{{title}}</h1> <div class="body"> //{{body}} </div> </div>
script标签加载模版到浏览器中 node环境预编译 把html代码插入
1 <script id="entry-template" type="text/x-handlebars-template"> template content </script> var source = $("#entry-template").html(); var template = Handlebars.compile(source);template
1 //这样输入 var context = {title: "My New Post", body: "This is my first post!"} var html = template(context); //可以编译得到 <div class="entry"> <h1>My New Post</h1> <div class="body"> This is my first post! </div> </div>三个花括号 可以编译html
1 <div class="entry"> <h1>{{title}}</h1> <div class="body"> //{{{body}}} </div> </div> //数据 { title: "All about <p> Tags", body: "<p>This is a post about <p> tags</p>" } //会得到 <div class="entry"> <h1>All About <p> Tags</h1> <div class="body"> <p>This is a post about <p> tags</p> </div> </div>unless
1 <div class="entry"> {{#unless license}} <h3 class="warning">WARNING: This entry does not have a license!</h3> {{/unless}} </div>if else
1 <div class="entry"> {{#if author}} <h1>{{firstName}} {{lastName}}</h1> {{else}} <h1>Unknown Author</h1> {{/if}} </div> <div class="entry"> {{#if author}} <h1>{{firstName}} {{lastName}}</h1> {{/if}} </div>each
1 {{#each paragraphs}} <p>{{this}}</p> {{else}} <p class="empty">No content</p> {{/each}} {{#each array}} {{@index}}: {{this}} {{/each}} {{#each object}} {{@key}}: {{this}} {{/each}}with
1 <div class="entry"> <h1>{{title}}</h1> {{#with author}} <h2>By {{firstName}} {{lastName}}</h2> {{/with}} </div> //数据 { title: "My first post!", author: { firstName: "Charles", lastName: "Jolley" } } //得到 <div class="entry"> <h1>My first post!</h1> <h2>By Charles Jolley</h2> </div>Handlebars.registerHelper
1 //页面 <div class="post"> <h1>By {{fullName author}}</h1> <div class="body">{{body}}</div> <h1>Comments</h1> {{#each comments}} <h2>By {{fullName author}}</h2> <div class="body">{{body}}</div> {{/each}} </div> //js var context = { author: {firstName: "Alan", lastName: "Johnson"}, body: "I Love Handlebars", comments: [{ author: {firstName: "Yehuda", lastName: "Katz"}, body: "Me too!" }] }; Handlebars.registerHelper('fullName', function(person) { return person.firstName + " " + person.lastName; }); //编译后 <div class="post"> <h1>By Alan Johnson</h1> <div class="body">I Love Handlebars</div> <h1>Comments</h1> <h2>By Yehuda Katz</h2> <div class="body">Me Too!</div> </div>安全转义
new Handlebars.SafeString('<div>HTML Content!</div>')
注释
1 {{! xxx}}和{{!-- xxx --}}