Handlebars 模板引擎,及在 node 项目中使用

Handlebars 模板引擎,及在 node 项目中使用

说明

Handlebars,是一个语义化的模板,它看起来和 HTML 一样,只是嵌入了 handlebars 表达式。

1. 在 node 项目中的使用

1. express 项目文件配置
    yarn add express # 4.16.2
    yarn add express-handlebars # 3.0.0
    const express = require('express');
    const http = require('http');
    const path = require('path');

    const app = express();
    const exphbs = require('express-handlebars'); // 引入 hanlebars 解析

    // 设置模板为 handlebars
    app.set('views', path.join(__dirname, 'views'));
    const hbs = exphbs.create({
       extname: '.hbs', // 设置文件后缀
       layoutsDir: ['views/'] // 设置模板文件的目录
    })
    app.engine('hbs', hbs.engine); // 设置其模板引擎,名称为 'hbs'
    app.set('view engine', 'hbs'); // 将当前默认模板引擎设置为 ’hbs‘

    app.all('/', function (req, res, next) {
       res.render('home', {name: 'xxx'}); // 传入变量数据,也可以设置为 app.locals 的值
    })

    const server = http.createServer(app);

    server.listen('8456', function () {
       console.log('\nexpress server start at http://localhost:' + 8456);
    })
2. koa 项目文件配置
    yarn add koa # 2.4.1
    yarn add koa-router # 7.3.0
    yarn add koa-views # 6.1.3
    const Koa = require('koa');
    const Router = require('koa-router');
    const views = require('koa-views'); // 用来处理各种模板编译
    const path = require('path');

    const app = new Koa();
    const router = new Router();

    // 添加处理模板的中间件
    app.use(views(path.join(__dirname, 'views'), {
       map: {hbs: 'handlebars'}
    }))

    router.get('/', async (ctx, next) => {
       await ctx.render('home.hbs', {name: 'yyy'}); // 也可以使用 ctx.state 的数据
    })

    app.use(router.routes());
    app.use(router.allowedMethods())

    app.listen('7654', function () {
       console.log('server in http://localhost:' + 7654);
    })

2. API 详解

静态的代码与 HTML 一致

1. 渲染变量
  • Handlebars 通过 {{expression}} 双大括号渲染变量,并且变量会经过编码
  • 如果不希望编码可以使用 {{{expression}}} 三个大括号
    <div>
        转码后 {{script}}
    </div>
    <div>
        未转码渲染为标签 {{{script}}}
    </div>
2. 渲染列表 each helper
  • this 表示当前上下文,用来访问当前项
  • @index 表示当前列表的索引
  • else 用来定义没有数据时的显示
  • @key 当遍历的是对象时,@key 表示属性名 this 为属性值
   <ul>
      {{#each members}}
         <li>member is {{this}},index is {{@index}}</li>
      {{else}}
         <li>this is empty</li>
      {{/each}}
      <p> ==== === ==== ===== ===== </p>
      {{!-- list: [{name: '', age: ''}] --}}
      {{#each list}}
         <li>name: {{name}}, age: {{age}}</li>
      {{else}}
         <li>this is empty</li>
      {{/each}}
      {{!-- obj: {name: '', age: '', tel: ''} --}}
      {{#each obj}}
         <li>{{this}} -- {{@key}}</li>
      {{/each}}
   </ul>
3. 渲染对象 with helper

with 可以改变当前上下文

   <div>
      {{!-- obj: {name: '', age: '', tel: ''} --}}
      {{#with obj}}
         <p>{{name}} : {{age}} : {{tel}}</p>
      {{/with}}
   </div>
4. 条件渲染 if helper
  • if true 渲染
  • unless false 渲染
   <div>
      {{!-- name: '' --}}
      {{#if name}}
         <p>name is {{name}}</p>
      {{else}}
         <p>empty</p>
      {{/if}}
   </div>
   <div>
      {{!-- name: '' --}}
      {{#unless name}}
         <p>name is {{name}}</p>
      {{else}}
         <p>empty</p>
      {{/unless}}
   </div>
5. 路径

Handlebars 支持简单的嵌套路径,便于属性查找

   <div>
      {{!-- content: {body: {link: '', members: []}} --}}
      {{content.body.link}}
      {{!-- with 者部分作用是让 members 所在作用域对应的对象位置为 body 内部 --}}
      {{#with content.body}}
         {{#each members}}
            <p>name: {{name}}</p>
            <p>currentLink: {{this.link}}</p>
            <p>link: {{../link}}</p>
         {{/each}}
      {{/with}}
   </div>
6. 注释
   <div>
      {{! 这种注释不会出现在编译后的 HTML 中 }}
      <!-- 这种注释会出现在编译后的 HTML 中 -->
      {{!-- 
         这种注释是多行注释
       --}}
   </div>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值