The characteristics of
- Efficiently build semantic templates
- Handlebars is basically compatible with the Mustache template.
- Handlebars compiles templates into JavaScript functions, which are fast to execute.
The installation
- Through CDN:
<script src="https://cdn.jsdelivr.net/npm/handlebars@latest/dist/handlebars.js"></script>
Define the template
Simple expression
var template = Handlebars.compile(` < p > simple expression < / p > < p > {{firstname}} - {{lastname}} < / p > `);
var output = template({
firstname: "xiao".lastname: "xin"
})
Copy the code
Nested input objects
var template = Handlebars.compile(Input object ` < p > nested < / p > < p > {{person. Firstname}} - {{person. The lastname}} < / p > `);
var output = template({
person: {
firstname: "tong".lastname: "xue"}})Copy the code
Computing context
with
Omit context
var template = Handlebars.compile(Calculation context ` < p > < / p > < p > {{# with person}} {{firstname}} - {{lastname}} {{/ with}} < / p > `);
var output = template({
person: {
firstname: "tong".lastname: "xue"}})Copy the code
each
Use this instead of context
var template = Handlebars.compile(Calculation context ` < p > < / p > < p > {{# each people}} < li > < / li > {{this}} {{/ each}} < / p > < p > {{# each persons}} < li > {{this. The name}} < / li > {{/each}} `);
var output = template({
persons: [{name: 'zhang' },
{ name: 'wang'}].people: [
"Yehuda Katz"."Alan Johnson"."Charles Jolley"]})Copy the code
Template annotation
<! This comment will show upas HTML-comment -->
{{! This comment will not show up inthe output}} {{! -- This comment may contain mustaches like }} --}}Copy the code
Custom assistant
// Filters are used to format content
Handlebars.registerHelper('loud'.function (aString) {
return aString.toUpperCase()
})
// We can do more processing after we get the object
Handlebars.registerHelper('print_person'.function () {
return this.name
})
Copy the code
Block helper code
// High customizability
Handlebars.registerHelper("list".function (items, options) {
const itemsAsHtml = items.map(item= > "<li>" + options.fn(item) + "</li>");
return "<ul>\n" + itemsAsHtml.join("\n") + "\n</ul>";
});
Copy the code
other
- HTML escape using {{{three into the package}}}
- Change context:.. / Get the parent