第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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值