首先在项目文件夹下使用 cmd,输入:npm install --save art-template koa-template
art-template语法参考:http://aui.github.io/art-template/zh-cn/docs/syntax.html,同时也支持ejs模板语法
后端:
//koa-art-template模板引擎 const koa = require('koa'); var router = require('koa-router')(); var render = require('koa-art-template'); const static = require('koa-static'); const bodyParser = require('koa-bodyparser'); const session = require('koa-session'); var app = new koa(); app.use(static('./www')); app.use(bodyParser()); var keys = []; (()=>{ for(var i=0;i<1000;i++){ keys.push(Math.random()+100); }; }); app.keys = keys; app.use(session({ maxAge:1000, keys:'koa:sess' },app)); /* render(app,{ root:'模板路径', extname:'.art', //模板文件尾 debug: process.env.NODE_ENE !== 'production' //打印报错 }); */ render(app,{ root:'views', extname:'.art', debug: process.env.NODE_ENV !== 'production' }); router.get('/',async (ctx)=>{ await ctx.render('index'); }); app.use(router.routes()); app.use(router.allowedMethods()); app.listen(80);
文件目录结构:
前端:
<!DOCTYPE html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]--> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title></title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href=""> </head> <body> <!--[if lt IE 7]> <p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="#">upgrade your browser</a> to improve your experience.</p> <![endif]--> <div style="width: 200px;height: 200px;background: black;"></div> {{ '123' }} <script src="" async defer></script> </body> </html>
效果: