Nodejs—jade模版和ejs模版
// 整个网站的内容不可能都是静态(写在html中的固定数据)的,模版引擎其实就是渲染页面,把从数据中获取的数据,动态渲染到页面。
//
// jade
// 与普通的html、css不能共存,强依赖 如果用了就要一直用
// 使用 cnpm install jade
// ejs
// 不会破坏html、css只是在html添加内容, 弱依赖,可以拿掉
// 使用 cnpm install ejs
jade模版
准备工作:新建1.jade文件
第一步:cnpm install jade
***第二步:1.jade***格式有些奇怪
html
head
div 这是head
body
p 这是body
第三步:新建一个js文件
const jade = require('jade');
// {pretty: true} 格式化
console.log(jade.renderFile('./www/1.jade', {pretty: true}));
效果:
ejs模版
准备工作:新建1.ejs文件
第一步:cnpm install ejs
***第二步:1.ejs***格式有些奇怪
<!--快速生成html模版 先输入!再点击tab键-->
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
// 和百度模版很像
<h1>我的名字: <%= name %>></h1>
<% for (var i = 0; i < age.length; i++) { %>
<p>我的年龄:<%= age[i] %></p>
<%}%>
<%= html%>
<%- html%>
</body>
<!-- = html转译,一般都转译-->
<!-- - html不转译-->
</html>
第三步:新建一个js文件
const ejs = require('ejs');
ejs.renderFile(
'./www/1.ejs',
{
name: 'poppy',
age: [10, 20, 30, 40],
html: '<div>div标签</div>'
},
(err, data) => {
if (err) {
console.log('错误')
} else {
console.log(data)
}
})
效果:
esj的include引入其他模版
准备工作:新建header.ejs文件,2.ejs引入
2.ejs
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<% include ./header.ejs %>
<p>2.ejs的内容</p>
</body>
</html>
效果:
include引入css样式
include.js
const ejs = require('ejs');
ejs.renderFile('./www/2.ejs', {type: 'yellow'}, (err, data) => {
if (err) {
console.log('错误');
} else {
console.log(data)
}
})
2.ejs
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<% include ./header.ejs %>
<p>2.ejs的内容</p>
<!-- 引入css样式-->
<% if (type == 'red') { %>
<% include ./css/red.css %>
<% } else {%>
<% include ./css/yellow.css %>
<% } %>
</body>
</html>
header.ejs
<h2>外部引入的头部</h2>