第4章-模板引擎Jade和Handlebars-4.5.單獨使用Handlebars

可以通過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>&#x27;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>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章