onvno / pokerface

日常技术文章阅读整理
3 stars 0 forks source link

20190314 - koa模板渲染 #5

Open onvno opened 5 years ago

onvno commented 5 years ago

基础方法

koa2加载模板引擎:此文档为KOA进阶ebook,有时间可以看看

const Koa = require('koa')
const views = require('koa-views')
const path = require('path')
const app = new Koa()

// 加载模板引擎
app.use(views(path.join(__dirname, './view'), {
  extension: 'ejs'
}))

app.use( async ( ctx ) => {
  let title = 'hello koa2'
  await ctx.render('index', {
    title,
  })
})

app.listen(3000)

注意:需要安装ejs

路由配合模板渲染

  router.get('/test', async (ctx, next) => {
    await ctx.render('templateName', {
      title
    }) 
  })