由於版權問題,現已改名pug.但無須擔心,幾乎沒什么區別.就算依然使用jade也不會有太大影響. 慢慢遷移過渡即可
# 官網
https://pugjs.org
# github https://github.com/pugjs/pug
# 文檔地址
https://pugjs.org/language/inheritance.html
# 入門指南
https://pugjs.org/api/getting-started.html
安裝pug
# 全局安裝cli npm install pug-cli -g # 本地安裝 npm install pug --save-dev
為了符合大眾教材,依然使用jade也無傷大雅
# 創建文件夾和文件 mkdir jade-test && touch index.js index.jade # 安裝依賴 npm init -y && cnpm install jade --save # 安裝全局jade cnpm install jade -g
index.jade
.header
h1 #{title}
p .body p #{body} .footer div #{By} a(href="http://www.baidu.com/#{author.twitter}") #{author.name} ul each tag, index in tags li #{tag}
index.js
var jade = require('jade') var fs = require('fs') var data = { title : "my title", author: { twitter: "@Lee", name: "Azat" }, tags: ['express', 'node', 'javascript'] } data.body = process.argv[2] // jade.compile fs.readFile('index.jade', 'utf-8', function (error, source) { var template = jade.compile(source); var html = template(data) console.log(html); }) // jade.renderFile jade.renderFile('index.jade', data, function (error, html) { console.log(html) })
運行jade: node index.js 'email body'
block 和 extends 、append(后) / prepend(前)
# API官方文檔
https://pugjs.org/language/inheritance.html
layout.pug
doctype html
html(lang='en') head title= appTitle body block content footer block footer | © 2009-2017 CyLeeBlog.com 版權所有 ICP證:粵S-172RM
index.pug
extends ./includes/layout.pug
block content
h1 #{title}
p Welcome to #{title}
block append footer script | window.alert('123')
login.jade
extends ./includes/layout.pug
block content
h1= title form(method="post") | 用戶名: input(name="name") br | 密碼: input(nane="pwd")
運行效果圖如下: 可以看到不僅繼承了 layout,在 content 塊中添加了個性內容, 還成功的往 footer 塊中添加了腳本,進一步靈活和個性化:
除了學到 block 和 extends、append / prepend 的配合使用。還知道了。只要你不是變量,或者說你想以字符串開始。標簽的后面必須是“|”來聲明。才能正常使用字符串或者 Javascript 腳本。而如果是字符串和變量嵌套,則變量需要使用#{變量}的形式書寫。非常簡單.
使用cli快速編譯為html
(注:需要先安裝全局pug-cli)
layout.pug
doctype html html(lang='en') head title= title body h1= title p Welcome to #{title} ul li a(href="/") home li a(href="/login") login li a(href="/reg") reg block content footer block footer | © 2009-2017 CyLeeBlog.com 版權所有 ICP證:粵S-172RM
命令行輸入:
# 查看幫助 pug --help # 編譯為html pug .\layout.pug -p layout.html # 編譯並且賦值 pug .\layout.pug -O "{title: 'fuck you'}" .\layout.html # 監聽並且實時改變html pug .\layout.pug -w layout.html
if 條件判斷
https://pugjs.org/language/conditionals.html
layout.pug
doctype html html(lang='en') head title= title body h1= title p Welcome to #{title} ul li a(href="/") home if user li a(href="/login") publish li a(href="/reg") logout else li a(href="/login") login li a(href="/reg") reg article if success div= success if error div= error block content footer block footer | © 2009-2017 CyLeeBlog.com 版權所有 ICP證:粵S-172RM