koa art-template模板引擎

优势:速度极快,能接近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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值