1. 安装:
// 新建项目 koa-demo
npm init
npm install koa koa-router --save
npm install koa-swig --save
2. 图示:
3. app.js 代码:
const Koa = require('koa');
const Router = require('koa-router');
const Swig = require('koa-swig'); // 1. 引入模块 swig
const co = require('co');
const app = new Koa();
const router = new Router();
app.context.render = co.wrap(Swig({ // 2. 配置
root: __dirname + '/views', // 视图文件路径
autoescape: true, // false:解析模板数据中的html
cache: false, // 'memory':请用缓存,避免每次刷新页面都去解析模板
ext: 'html'
}))
let datas = { // 自定义 数据
appName: 'ToDoList',
tasks: [
{ id: 1, title: '测试任务一', done: true },
{ id: 2, title: '学习koa', done: false },
{ id: 3, title: '学习sequelize', done: false },
]
}
router.get('/', async (ctx, next) => {
ctx.body = await ctx.render('index.html', { datas }); // 3. 使用
})
app.use(router.routes())
app.listen(8879);
4. index.html 代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="/static/index.css">
</head>
<body>
<!-- 1. 渲染数据 {{}} -->
<h2>{{datas.appName}}</h2>
<a href="/add">添加新任务</a>
<hr>
<ul>
<!-- 2. for 循环 -->
{% for task in datas.tasks %}
<!-- 3. if else 判断 -->
{% if task.done %}
<li class="{{name}}">
<input type="checkbox" checked>
{{task.id}} - {{task.title}}
<a href="">删除</a>
</li>
{% else %}
<li class="{{name}}">
<input type="checkbox">
{{task.id}} - {{task.title}}
<a href="">删除</a>
</li>
{% endif %}
{% endfor %}
</ul>
</body>
</html>
5. koa-swig 语法:
1. swig使用指南
http://www.iqianduan.net/blog/how_to_use_swig
https://www.jianshu.com/p/3b4354c6bc36
2. swig官方文档
http://node-swig.github.io/swig-templates/docs/