起步下載pughtml
npm i pug複製代碼
渲染模板文件:npm
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複製代碼
相關解釋:緩存
上面的index.pug將被渲染成bash
<! 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.jskoa
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')
}
})複製代碼
起步jsp
npm i ejs複製代碼
渲染模板文件async
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>複製代碼
相關解釋:
上面模板渲染爲下面格式
<!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]
})
});
複製代碼