可以通過NPM安裝Handlebars,用命令$npm install handlebars
或$npm install handlebars --save.
示例:
handlebars-example.js文件如下:
var handlebars = require('handlebars'),
fs = require('fs');
var data = {
title: 'practical node.js',
author: {
name: 'lijian',
weibo: 'weibo@lijian'
},
tags: ['express', 'node', 'javascript']
}
data.body = process.argv[2];
fs.readFile('handlebars-example.html', 'utf-8', function(error, source){
handlebars.registerHelper('custom_title', function(title){
var words = title.split(' ');
for (var i = 0; i < words.length; i++) {
if (words[i].length > 4) {
words[i] = words[i][0].toUpperCase() + words[i].substr(1);
}
}
title = words.join(' ');
return title;
})
var template = handlebars.compile(source);
var html = template(data);
console.log(html)
});
文件handlebars-example.html中用到了helper custom_title,裏面有用他輸出屬性的用法:
<div class="header">
<h1>{{custom_title title}}</h1>
</div>
<div class="body">
<p>{{body}}</p>
</div>
<div class="footer">
<div><a href="http://weibo.com/{{author.weibo}}">{{author.name}}</a>
</div>
<ul>
{{#each tags}}
<li>{{this}}</li>
{{/each}}
</ul>
</div>
當運行$node handlebars-example.js 'email body'
時,會生成下面的HTML:
<div class="header">
<h1>Practical Node.js</h1>
</div>
<div class="body">
<p>'email</p>
</div>
<div class="footer">
<div><a href="http://weibo.com/weibo@lijian">lijian</a>
</div>
<ul>
<li>express</li>
<li>node</li>
<li>javascript</li>
</ul>
</div>