優勢:速度極快,能接近js的極限速度
1、安裝
npm install --save art-template
npm install --save koa-art-template
2、引入
const render = require('koa-art-template');
const path=require('path');
3、配置模板引擎
render(app, {
root: path.join(__dirname, 'views'), //配置模板引擎路徑
extname: '.html', //以什麼後綴結尾
debug: process.env.NODE_ENV !== 'production' //在開發階段開啓debug
});
4、渲染數據
await ctx.render('/x',{參數鍵值對})
5、獲取數據
方式一:ejs調用數據語法
方式二:{{}}
{{鍵名}}
{{@鍵名}} 能夠解析html標籤
循環:
{{each 數據}}
{{$index}}--{{$value}}
{{/each}}
6、引入外部模板
{{include '模板路徑/x.html'}}
代碼示例:
server.js:
const Koa=require('koa');
const Router=require('koa-router');
// const views=require('koa-views');
const commonm=require('./public/common');
const bodyParser=require('koa-bodyparser');
const static=require('koa-static');
const render = require('koa-art-template');
const path=require('path');
const app=new Koa();
const router=new Router();
//配置模板引擎
// app.use(views('views',{extension:"ejs" })); //文件後綴必須爲.ejs
// app.use(views('views',{map:{html:'ejs'}}));
render(app, {
root: path.join(__dirname, 'views'), //配置模板引擎路徑
extname: '.html', //以什麼後綴結尾
debug: process.env.NODE_ENV !== 'production' //在開發階段開啓debug
});
//配置static
app.use(static('static'));
app.use(router.routes())
.use(router.allowedMethods());
app.use(bodyParser());
router.get('/',async(ctx,next)=>{
await ctx.render("index",{
title:'jeff',
info:"<h2 style='color:red'>渲染</h2>"
});
})
router.get('/news',async(ctx,next)=>{
await ctx.render('news',{
names:"jeff",
h:'<h2>jjj</h2>',
list:[1,2,3,4]
})
})
//路由中間件
router.get('/det',async(ctx,next)=>{
// ctx.body='det1';
console.log('aaa');
await next();
})
router.get('/det',async(ctx,next)=>{
ctx.body='det2';
})
router.post('/info',async (ctx,next)=>{
// var data=await commonm.Posts(ctx);
var data=ctx.request.body.name;
ctx.body=data;
})
router.get('/msg',async(ctx,next)=>{
ctx.body=ctx.query.id;
})
//動態路由
router.get('/home/:aid/:aic',async(ctx,next)=>{
ctx.body=ctx.params.aid+ctx.params.aic;
})
app.listen(3000,()=>{
console.log('this koa server is running at http://localhost:3000/');
})
news.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<ul>
koa art
<li><%=name%></li>
{{names}}
{{1+2}}
{{@h}}
<%-h%>
{{include './public/1.html'}}
{{each list}}
{{$index}}--{{$value}}
{{/each}}
</ul>
</body>
</html>