Pug
起步下载pug
npm i pug渲染模板文件:
index.pug
doctype
html
heade
meta(charset="utf-8")
meta(name="site",content="test)
title= title
script.
window.onload=function(){
let oDiv=document.getElementById('div1');
oDiv.onclick=function(){
}
}
body
h1 一级标题
ul
each user in users
li(class='user-item clearfix')
span(class='f1 name')=user.name
span(class='f1')=user.password相关解释:
- pug利用缩进来表示嵌套关系
- 元素中的属性用括号表示
- 元素中的内容(一个普通内容可以在元素加一个缩进表示,变量数据内容可以在元素后面衔接等号然后加上变量,多个内容可以在元素后面加 . 然后缩进表示)
- each是pug中的内置循环函数
上面的index.pug将被渲染成
<! doctype />
<html>
<heade>
<meta charset="utf-8" />
<meta name="site" content="test/>
<title>标题</title>
<script>
window.onload=function(){
let oDiv=document.getElementById('div1');
oDiv.onclick=function(){
}
}
</script>
</heade>
<body>
<h1>一级标题</h1>
<ul>
<li class='user-item clearfix'>
<span class='f1 name'>blue</span>
<span class='f1'>123</span>
</li>
<li class='user-tem clearfix'>
<span class='f1 name'>red</span>
<span class='f1'>234</span>
</li>
<li class='user-item clearfix'>
<span class='f1 name'>green</span>
<span class='f1>345</span>
</li>
</ul>
</body>
</html>模板引擎
pug.js
const pug = require('pug');
// 设置模板引擎,第一个参数为渲染文件位置,第二个是放置参数或者数据,第三个是回调函数
pug.renderFile('./index.pug',{
//此处放数据或者参数
pretty: true, //服务端渲染代码缩进
title: '标题', //变量
// users数组
users: [
{name:'blue',password:'123'},
{name:'red',password:'234'},
{name:'green',password:'345'}
]
},(err,data)=>{
if(err){
console.log(err)
}esle{
console.log('success')
}
})ejs
起步
npm i ejs渲染模板文件
header.ejs
<header>
<nav>
xxxx
</nav>
</header>index.ejs
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<% include header.ejs -%>
<%
let a=12;
let b=6;
-%>
<%=a+b -%>
<%arr.forEach(item=>{%>
<div class="">
<%=item%>
</div>
<%})%>
</body>
</html>相关解释:
- ejs类似Java的jsp用法,在<% %>内填写函数、声明变量,并且支持Es6的语法
- include header.ejs是在该文件中引入header.ejs文件
- 只要在<% %>外面声明的变量,如果没有在<% %>声明的话,只能表示是字符串,而不是变量
上面模板渲染为下面格式
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<header>
<nav>
xxxx
</nav>
</header>
18
<div class="">
123
</div>
<div class="">
54
</div>
<div class="">
64
</div>
</body>
</html>服务器渲染
const ejs=require('ejs');
ejs.renderFile('./template/2.ejs', {
name: 'blue',
arr: [123, 54, 64]
}, (err, data)=>{
if(err){
console.log('错了', err);
}else{
console.log(data);
}
});koa-ejs使用
const Koa=require('koa');
const ejs=require('koa-ejs');
const path=require('path');
let server=new Koa();
server.listen(8080);
// 模板引擎设置
ejs(server, {
// 模板文件
root: path.resolve(__dirname, 'template'),
layout: false,
viewExt: 'ejs', // 扩展名
cache: false, // 服务器缓存
debug: false
});
//
server.use(async ctx=>{
await ctx.render('2', {
arr: [12, 5, 8, 99, 37]
})
});