发表日期:2018-11 文章编辑:小灯 浏览次数:1019
image.pngsearver/index.js
const Koa = require('koa') const app = new Koa() const { normal } = require('./tpl')app.use(async (ctx,next)=>{ ctx.type='text/html;charset=utf-8' ctx.body =normal })app.listen(8888) server/tpl/index.js
const normalTpl=require('./normal') module.exports={ normal:normalTpl } server/tpl/normal.js
module.exports=` <!DOCTYPE html> <html><head> <meta charset=utf-8> <meta name=viewport content="width=device-width,initial-scale=1"> <title>vuetest</title> <link rel="stylesheet" href="https://cdn.bootcss.com/twitter-bootstrap/4.1.3/css/bootstrap.css"> </head> <body> <div class="container"> <div class="row"> <div class="col-md-6">This is </div> <div class="col-md-6">This is normal</div> </div> </div> </body> </html> ` 这里使用的是pug模板引擎+koa-views中间件,
npm i koa-views pug -S
1.searver/index.js
const Koa = require('koa') const app = new Koa() // const views = require('koa-views') const { resolve } =require('path') //使用中间件 app.use(views(resolve(__dirname,'./views'),{ extension:'pug' }))app.use(async (ctx,next)=>{ //模板使用及传参 await ctx.render('index',{ you:'luck', me:'lqs' }) })app.listen(8888) server/views/index.pug
htmlhead 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.css")body .container.row .col-md-6 h1 Hi #{you} p This is #{me} .col-md-6 p 测试动态pug模板引擎 进一步优化目录结构
image.pngserver/views/index.pug
extends ./layouts/default block titletitle koa douban shouye block content.container.row .col-md-6 h1 Hi #{you} p This is #{me} .col-md-6 p 测试动态pug模板引擎 server/views/layouts/default.pug
htmlhead meta(charset='utf-8') meta(name=viewport content="width=device-width,initial-scale=1") block title include ../includes/stylebody block content include ../includes/script