handlebars: 一个好用的模板引擎/hbs

为什么选择这个,因为ejs不太好用
更新于: 2023-09-01 17:03:20

cheatsheet

一些常用的语法参考列表。

功能数据模板
变量
{
  "firstname": "Yehuda",
  "lastname": "Katz"
}
<p>{{firstname}} {{lastname}}</p>
with 作用域
{
  person: {
    firstname: "Yehuda",
    lastname: "Katz",
  },
}
{{#with person}}
{{firstname}} {{lastname}}
{{/with}}
each 循环
{
  people: [
    "Yehuda Katz",
    "Alan Johnson",
    "Charles Jolley",
  ],
}
<ul class="people_list">
  {{#each people}}
    <li>{{this}}</li>
  {{/each}}
</ul>
自定义helper
Handlebars.registerHelper('loud', function (aString) {
    return aString.toUpperCase()
})
{{firstname}} {{loud lastname}}
partials
var data = {
  persons: [
    { name: "Nils", age: 20 },
    { name: "Teddy", age: 10 },
    { name: "Nelson", age: 40 },
  ],
};

Handlebars.registerPartial(
    "person", 
    "{{person.name}} is {{person.age}} years old.\n"
)
{{#each persons}}
  {{>person person=.}}
{{/each}}
类似 include位置: partials/header/top.hbs
{{> header/top}}
if
{
  author: true,
  firstName: "Yehuda",
  lastName: "Katz",
}
<div class="entry">
{{#if author}}
<h1>{{firstName}} {{lastName}}</h1>
{{/if}}
</div>
unless
{}
<div class="entry">
{{#unless license}}
<h3 class="warning">WARNING: This entry does not have a license!</h3>
{{/unless}}
</div>

参考