在部署這個基於Hexo的Blog的時候,發現Hexo的Themes都使用 .pug 檔案, PUG 是什麼?

PUG 是什麼?

PUG 是一種 HTML 模板語言,支援編寫 JavaScript 邏輯,省略了 HTML 的開、閉合標籤,看上去更加簡潔

本頁版權聲明的 Pug 原始碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
.article
hr
h2 版權聲明
- var articleName = theme.copyright.name || config.author
- var articleUrl = theme.copyright.url || config.url
- var pageLink = page.permalink
- var licensePath = 'http://creativecommons.org/licenses/by-nc-sa/4.0/'
!= '| 作者:'
a(href=url_for(articleUrl))=articleName
br
!= '| URL:'
a(href=url_for(pageLink))=pageLink
br
!= '| 許可協議:'
a(href=url_for(licensePath)) #{'知識共享署名-非商業性使用-相同方式共享 4.0 國際許可協議'}
hr

在簡潔的同時,Pug也有好多缺點:例如在使用第三方開發套件的示例Code時,大部分皆為HTML,需要重寫為Pug才能使用。Pug在簡潔的同時也在降低可讀性,提升維護難度

筆者這樣的 Back-end development,還是HTML好

撰寫 pug

Pug 相比 HTML 最大的不同是去掉了開、閉合標籤,結構和HTML相同

  • 這裡為了方便比對,將會使用前者PUG,後者HTML的寫法

結構單元

  • PUG
    1
    2
    section(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
    7
    a(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
    2
    div.testClass
    div#idName
  • HTML
    1
    2
    3
    <div class="testClass">
    <div id="#idName">
    </div>

    註解

  1. 單行註解
    • PUG
      1
      // 註解
    • HTML
      1
      <!-- 註解 -->
  2. 單行註解,不渲染
    • PUG
      1
      2
      //- 註解
      .testClass
    • HTML
      1
      <div class="testClass">
  3. 多行註解
    • PUG
      1
      2
      3
      4
      5
      6
      // 註解註解註解註解註解註解
      註解註解註解註解註解註解
      註解註解註解註解註解註解
      //- 註解註解註解註解註解註解
      註解註解註解註解註解註解
      註解註解註解註解註解註解
    • HTML
      1
      2
      3
      <!-- 註解註解註解註解註解註解
      註解註解註解註解註解註解
      註解註解註解註解註解註解 -->

文字

標籤內的文字需要在tag後空一格撰寫

  • PUG
    1
    p 我係一個人
  • HTML
    1
    <p>我係一個人</p>

PUG 官網