Web前端必做笔记之一:Nunjucks基础使用
在上一节我们说到引入Nunjucks 现在我们用ctx来渲染模版 views下面的模版index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>公共模版</title>
</head>
<body>
<h1>我的第一个模版文件</h1>
</body>
</html>
server.js中
const Koa = require('koa');
const router = require('koa-router')();
const views = require('koa-views');
const nunjucks = require('nunjucks');
const app = new Koa();
app.use(views(__dirname + "/views",{
map:{html:'nunjucks'}
}))
app.use(async (ctx ) => {
await ctx.render("index")
})
app.use(router.routes());
app.listen(3000, () => {
console.log("server running")
})
再使用命令nodemon server.js 启动成功,就实现了Nunjucks来渲染 这个html文件 我们现在来加一些动态的数据,h1标签里修改为后台的数据,那要怎么修改呢? server.js中
const Koa = require('koa');
const router = require('koa-router')();
const views = require('koa-views');
const nunjucks = require('nunjucks');
const app = new Koa();
app.use(views(__dirname + "/views",{
map:{html:'nunjucks'}
}))
app.use(async (ctx ) => {
await ctx.render("index",{title:"hello nunjucks"})
})
app.use(router.routes());
app.listen(3000, () => {
console.log("server running")
})
index.html中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>公共模版</title>
</head>
<body>
<h1>{{title}}</h1>
</body>
</html>
这样再重新启动服务器,就会看到,hello nunjucks. 通过render的第二个参数把一个数据传递给模版,这就是模版数据传递的方法
|