首页 > 代码库 > Hogan模板

Hogan模板

基础示例
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}}‘
			 + ‘<p>Name: {{name}}, Age: {{age}} years old</p>‘
			 + ‘{{/students}}‘;
var context = {
	students: [
		{ name: ‘Jane Narwhal‘, age: 21 },
		{ name: ‘Rick LaRue‘, age: 26 }
	]
};
var template = hogan.compile(template);

console.log(template.render(context));
//输出结果:<p>Name: Jane Narwhal, Age: 21 years old</p><p>Name: Rick LaRue, Age: 26 years old</p>
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 = ‘<p>Name: {{name}}, ‘
					+ ‘Age: {{age}} years old</p>‘;
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);
//输出结果:<p>Name: Jane Narwhal, Age: 21 years old</p><p>Name: Rick LaRue, Age: 26 years old</p>







Hogan模板