淺談前端模板pug
2021-08-03 | 前端 · | Full Stand developer
在部署這個基於Hexo的Blog的時候,發現Hexo的Themes都使用 .pug 檔案, PUG 是什麼?
PUG 是什麼?
PUG 是一種 HTML 模板語言,支援編寫 JavaScript 邏輯,省略了 HTML 的開、閉合標籤,看上去更加簡潔
本頁版權聲明的 Pug 原始碼
1 | .article |
在簡潔的同時,Pug也有好多缺點:例如在使用第三方開發套件的示例Code時,大部分皆為HTML,需要重寫為Pug才能使用。Pug在簡潔的同時也在降低可讀性,提升維護難度
筆者這樣的 Back-end development,還是HTML好
撰寫 pug
Pug 相比 HTML 最大的不同是去掉了開、閉合標籤,結構和HTML相同
- 這裡為了方便比對,將會使用前者PUG,後者HTML的寫法
結構單元
- PUG
1
2section(class="testClass")
div(class="testClass2") - HTML
1
2
3<section class="testClass">
<div class="testClass2"></div>
</section>
閉合標籤
- PUG
1
img(src="./test.webp")/
- HTML
1
<img src="./test.webp" />
內聯:嵌套DIV
- PUG
1
.testClass: .testClass2 testText
- HTML
1
2
3<div class="testClass">
<div class="testClass2">testText</div>
</div>
屬性
可以使用逗號隔開,也可以不用。在屬性較多時可以豎排撰寫
- PUG
1
2
3
4
5
6
7a(href="//google.com.hk" class="testClass") Google
a(href="//google.com.hk", class="testClass") Google
input(
type="checkbox"
name="testInput"
checked
) - HTML
1
2<a href="//google.com.hk" class="testClass">Google</a>
<input type="checkbox" name="testInput" checked />
Class, ID
Class 同 ID 支援直接撰寫在 Tag 後方
- 單行註解
- PUG
1
// 註解
- HTML
1
<!-- 註解 -->
- PUG
- 單行註解,不渲染
- PUG
1
2//- 註解
.testClass - HTML
1
<div class="testClass">
- PUG
- 多行註解
- PUG
1
2
3
4
5
6// 註解註解註解註解註解註解
註解註解註解註解註解註解
註解註解註解註解註解註解
//- 註解註解註解註解註解註解
註解註解註解註解註解註解
註解註解註解註解註解註解 - HTML
1
2
3<!-- 註解註解註解註解註解註解
註解註解註解註解註解註解
註解註解註解註解註解註解 -->
- PUG
文字
標籤內的文字需要在tag後空一格撰寫
- PUG
1
p 我係一個人
- HTML
1
<p>我係一個人</p>