var hogan = require('hogan');var template = '{ {message}}';var context = {message: 'Hello template!'};var template = hogan.compile(template);console.log(template.render(context));//输出结果:Hello template
标签语法
- { {message}} 有转义功能
- { { {message}}} 没有转义功能
- { {! This is a comment}} 注释
- { {#students}} some code { {/students}} 遍历students变量
- { {^students}} some text { {/students}} 用以students变量不存在时,显示提示文本
var hogan = require('hogan');var template = '{ {#students}}' + 'Name: {
{name}}, Age: { {age}} years old' + '{ {/students}}';var context = { students: [ { name: 'Jane Narwhal', age: 21 }, { name: 'Rick LaRue', age: 26 } ]};var template = hogan.compile(template);console.log(template.render(context));//输出结果:Name: Jane Narwhal, Age: 21 years old
Name: Rick LaRue, Age: 26 years old
var hogan = require('hogan');var template = '{ {^students}}' + 'No students found' + '{ {/students}}';var context = { _students: [ { name: 'Jane Narwhal', age: 21 }, { name: 'Rick LaRue', age: 26 } ]};var template = hogan.compile(template);console.log(template.render(context));//输出结果:No students found
模板重用
var hogan = require('hogan');var studentTemplate = 'Name: {
{name}}, ' + 'Age: { {age}} years old';var mainTemplate = '{ {#students}}' + '{ {>student}}' + '{ {/students}}';var context = { students: [{ name: 'Jane Narwhal', age: 21 },{ name: 'Rick LaRue', age: 26 }]};var template = hogan.compile(mainTemplate);var partial = hogan.compile(studentTemplate);var html = template.render(context, {student: partial});console.log(html);//输出结果:Name: Jane Narwhal, Age: 21 years old
Name: Rick LaRue, Age: 26 years old