模板引擎用来生成html页面。jade模板引擎,比起html代码,相当于是用一种更简洁的书写语句来生成html页面。
比如:在jade中的 html 相当于<html></html>,br 相当于 <br />。jade可以智能地识别单双标签,还是挺省事的。
jade可以说是一种破坏式、强依赖的模板引擎,因为jade语句和html语句差异还是很大的。
jade使用总结如下:
1.根据缩进划分层级
2.属”性放在()里面,逗号分隔
<script src="a.js"></script>--------jade语法: script(src="a.js")
3.内容空个格,直接往后堆-----div aaa
<a href="http://www.zhinengshe.com/">官网</a>-----jade语法: a(href="http://www.zhinengshe.com/") 官网
4.特殊:style和class
style="width:200px;height:200px;background:red;"
(1)普通属性写法---div(style="width:200px;height:200px;background:red")
(2)用json---div(style= {width: '200px', height: '200px', background: 'red'})
class="aaa left-swrap active"
(1)普通属性写法---div(class="aaa left-warp active")
(2)用arr----div(class= ['aaa', 'left-warp', 'active'])
5.使用jade渲染页面
(1)jade.render('字符串');----- jade.render('html')
(2)jade.renderFile('模板文件名', 参数);-----jade.renderFile('./views/1.jade', { pretty: true }) //pretty:true美化代码
6.支持自定义标签
以下附上jade的代码:
1.jade,位于views目录下
html
head
style
script
body
div aaa
span bbb
ul
li
input(type="text",id="txt1",value="abc")
li
input(type="text",id="txt2",value="111")
a(href="http://www.baidu.com/") 百度
div(style="width:200px;height:200px;background:red")
div(style= {width: '200px', height: '200px', background: 'red'})
//div(title= {width: '200px', height: '200px', background: 'red'})
div(class="aaa left-warp active")
div(class= ['aaa', 'left-warp', 'active'])
//div(title= ['aaa', 'left-warp', 'active'])
div.box
div#div1
div(title="aaa",id="div1")
div&attributes({title: 'aaa', id: 'div2'})
jade1.js
const jade = require('jade');
const fs = require('fs');
//var str = jade.render('html');
var str = jade.renderFile('./views/1.jade', { pretty: true }) //pretty:true美化代码
//console.log(str);
//写入html
fs.writeFile('./build/a.html', str, function (err) {
if (err)
console.log('写入失败');
else
console.log('写入成功')
});
在当前目录下执行 node jade1.js,则在当前目录下的build目录下生成a.html文件,即1.jade渲染生成的html页面
a.html如下:
<html>
<head>
<style></style>
<script></script>
</head>
<body>
<div>aaa<span>bbb</span>
<ul>
<li>
<input type="text" id="txt1" value="abc"/>
</li>
<li>
<input type="text" id="txt2" value="111"/>
</li>
</ul>
</div><a href="http://www.baidu.com/">百度</a>
<div style="width:200px;height:200px;background:red"></div>
<div style="width:200px;height:200px;background:red"></div>
<!--div(title= {width: '200px', height: '200px', background: 'red'})-->
<div class="aaa left-warp active"></div>
<div class="aaa left-warp active"></div>
<!--div(title= ['aaa', 'left-warp', 'active'])-->
<div class="box"></div>
<div id="div1"></div>
<div title="aaa" id="div1"></div>
<div title="aaa" id="div2"></div>
</body>
</html>