koa2 动态模板渲染引擎中间件 koa-views + pug

koa2 的模板渲染有很多,比如pug(原 jade)、ejs 等等,这里以 pug 为例。同时使用 koa-views 中间件,将动态模板渲染集成到 koa2 中。

安装:npm install koa-views pug -s

pug 的 github 地址:https://github.com/pugjs/pug
koa-views 的 github 地址:https://github.com/queckezz/koa-views

新建一个简单的 server/index.js,代码如下:

const Koa = require('koa');
const app = new Koa();

const views = require('koa-views');
const { resolve } = require('path');

// view 接受两个参数,一个是根路径,一个是配置项
// 根路径我们可以设置成为 上一层的 views 文件夹,把所有 .pug 模板文件都到里面
// extension 是我们要使用的工具,这里使用 pug
app.use(views(resove(__dirname, './views'), {
  extension: 'pug'
}));

// 上一个中间件,会对 context 注入 render 方法,我们可以直接使用 render 方法渲染模板
// index 指的是 views 文件夹里面的 index.pug 文件,后缀名可以省略
// render 的第二个参数我们可以向模板文件传递变量。
app.use(async (ctx, next) => {
  await ctx.render('index', {
    name: 'bluescurry'
  });
})

views 文件夹中的 index.pug:

doctype html
html
  head
    meta(charset='utf-8')
    meta(name='viewport', content='width=device-width, initial-scale=1')
    title Koa Server Pug
    link(href='https://cdn.bootcss.com/twitter-bootstrap/4.1.3/css/bootstrap.min.css' rel='stylesheet')
    script(src='https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js')
    script(src='https://cdn.bootcss.com/twitter-bootstrap/4.1.3/js/bootstrap.bundle.min.js')
  body
    .container
      .row
        .col-md-8
          p I am #{name}
        .col-md-4
          p 测试动态 Pug 模板引擎

更多的 pug 语法详见官网:https://pugjs.org/api/getting-started.html
也可以看 Scott 老师的免费课程:https://www.imooc.com/learn/259


简单说一下 koa-views 的源码实现:

源码如下:

'use strict'

const { resolve } = require('path')
const debug = require('debug')('koa-views')
// 核心包,Template engine consolidation library.
const consolidate = require('consolidate')
// 发送静态文件
const send = require('koa-send')
// 获取路径
const getPaths = require('get-paths')
// 美化代码格式
const pretty = require('pretty')

module.exports = viewsMiddleware

function viewsMiddleware(
  path,
  { engineSource = consolidate, extension = 'html', options = {}, map } = {}
) {
  return function views(ctx, next) {
    if (ctx.render) return next()
    
    // 将 render 注入到 context 和 response 对象中
    ctx.response.render = ctx.render = function(relPath, locals = {}) {
      return getPaths(path, relPath, extension).then(paths => {
        const suffix = paths.ext
        const state = Object.assign(locals, options, ctx.state || {})
        // deep copy partials
        state.partials = Object.assign({}, options.partials || {})
        debug('render `%s` with %j', paths.rel, state)
        ctx.type = 'text/html'
        
        // 如果是 html 文件,不编译直接 send 静态文件
        if (isHtml(suffix) && !map) {
          return send(ctx, paths.rel, {
            root: path
          })
        } else {
          const engineName = map && map[suffix] ? map[suffix] : suffix
          
          // 使用 engineSource 配置的渲染引擎 render
          const render = engineSource[engineName]

          if (!engineName || !render)
            return Promise.reject(
              new Error(`Engine not found for the ".${suffix}" file extension`)
            )

          return render(resolve(path, paths.rel), state).then(html => {
            // since pug has deprecated `pretty` option
            // we'll use the `pretty` package in the meanwhile
            if (locals.pretty) {
              debug('using `pretty` package to beautify HTML')
              html = pretty(html)
            }
            ctx.body = html
          })
        }
      })
    }
    
    // 中间件执行结束
    return next()
  }
}

function isHtml(ext) {
  return ext === 'html'
}

很简单,一共就60多行代码,主要的功能是把 consolidate 改造为 koa2 的中间件。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Koa2-blog 2018-1-5 更新教程(新增上传头像、新增分页、样式改版、发布文章和评论支持markdow...
    wclimb阅读 13,093评论 1 53
  • 在node中使用模板引擎需要一个中间件koa-views 在koa中使用ejs 安装模块 使用模板引擎 demo源...
    夏夏夏夏顿天阅读 11,755评论 0 0
  • 框架提出的背景 ES6/7带来的变革 自ES6确定和ES7中async/await开始普及,Node的发展变得更加...
    宫若石阅读 12,733评论 1 14
  • afinalAfinal是一个android的ioc,orm框架 https://github.com/yangf...
    passiontim阅读 15,788评论 2 45
  • 我们的孤独与生俱来。 不知道在什么时候我开始关上自己悲伤压抑的一面,遇到一些事情习惯自己先消化。工作里的小事,我也...
    危绿啊阅读 1,130评论 0 0

友情链接更多精彩内容