在koa2中使用handlebars.js的layout的用法

本文介绍如何在Koa2中使用Handlebars模板引擎,并提供了详细的代码示例及使用心得,包括异步写法、自定义辅助函数等。

1. 前言

    koa是node.js的一个轻量级框架,与之搭配的模板引擎很多,如ejs,jade,handlebars等等。本人使用最多的handlebars.js,所以用这篇博客,来记录一下自己的使用心得

2.技术搭配

    在koa2使用handlebars.js,不要使用koa-views这个包,可以使用koa-hbs与koa-convert搭配就可以使用async/await的写法,代码如下

/* 
* @Author: 2861399191@qq.com
* @Date:   2018-06-24 17:04:16
* @Last Modified by:   lianglizhong
* @Last Modified time: 2018-08-04 15:06:01
*/

'use strict';
const koa=require("koa");
const app =new koa();
const convert=require("koa-convert");
const hbs = require('koa-hbs');//引入handlebars

const helpers = require('handlebars-helpers')({
  handlebars:hbs.handlebars
});//使用帮助方法
const path=require("path");
const serve = require('koa-static');
// const common= require("common");


hbs.registerHelper('fullName', function(person) {
   console.log("111-->",person);
   return `${person}111`
});




app.use(async(ctx,next)=>{
    Object.assign(ctx, {
      
      toValue(){
        console.log("添加到ctx方法上");
      }
    });
    await next();
});

app.use(serve(path.join(__dirname , './www')));
app.use(async(ctx,next)=>{

  const url=ctx.path;
  let  layout=null;
  ctx.toValue();

  console.log("url-->",url);
    const data = {
        title: 'my title',
        author: 'queckezz',
        "accounts": [
            { 'name': 'John', 'email': 'john@example.com' },
            { 'name': 'Malcolm', 'email': 'malcolm@example.com' },
            { 'name': 'David', 'email': 'david@example.com' }
        ]
    }


  // 对pjax进行判断
     
     console.log(ctx.headers["x-pjax"]);
     layout=ctx.headers["x-pjax"]?layout:"layout";
      console.log("layout-->",layout);
     await convert(hbs.middleware({
      viewPath: path.join(__dirname , './www'),
      layoutsPath: path.join(__dirname , './www'),
      partialsPath: path.join(__dirname , './www'),
      defaultLayout: layout,
      extname: ".html",
      disableCache: true
    }))(ctx,next)
  
  if(url==="/index"){
    console.log(122);
     await ctx.render('index',data);
  }

  if(url==="/other"){



    await ctx.render('other');
   
  }
  
})



app.listen(3012,()=>{
    console.log("模板引擎");
})

3.demo地址在 https://github.com/listtouch/koa2-koa-hbs-pjax.js (里面还使用了pjax.js 与NProgress.js)

转载于:https://my.oschina.net/u/2433463/blog/1922530

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值