美文网首页
koa2 动态模板渲染引擎中间件 koa-views + pug

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

作者: BluesCurry | 来源:发表于2018-12-13 14:56 被阅读0次

    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 的中间件。

    相关文章

      网友评论

          本文标题:koa2 动态模板渲染引擎中间件 koa-views + pug

          本文链接:https://www.haomeiwen.com/subject/fotbhqtx.html