網頁模板pug基本語法


該博客首發於www.litreily.top

Pug – robust, elegant, feature rich template engine for Node.js

pug原名jade,因版權問題更名為pug,即哈巴狗。與hexo默認模塊ejs一樣,pug也是一個模板引擎,可用於快速的網站開發,當然也可以用於靜態博客網站的設計。本站點現時所用主題manupassant也使用了pug

本文針對Hexo中使用pug的情況為例,說明其基本語法。

安裝

# common install
npm install pug

# install for hexo blog
npm install hexo-renderer-pug --save

語法

pug不同於html,前者不需要標簽的開和閉,如html<p>Demo</p>,在pug使用p Demo即可。

縮進

pug對空格敏感,有點類似python對制表符tab敏感。pug使用空格作為縮進符,當然用soft tab也可行。同一級標簽需保證左對齊。

div
    p Hello, world!
    p Hello, pug.

渲染結果如下:

<div>
    <p>Hellow, world!</p>
    <p>Hello, pug.</p>
</div>

注釋

pug使用//-//對代碼進行注釋,前者注釋內容不出現在渲染后的html文件中,后者反之。

//- html中不包含此行
// html中會包含此行

屬性

pug將標簽屬性存放於括號()內,多個屬性之間以逗號或空格分隔。此外,對於標簽的idclasspug使用#緊跟標簽id,使用.緊跟標簽class,可以同時設置多個class

h1#title Test title
img#name.class1.class2(src="/test.png" alt="test")

<h1 id="title">Test title</h1>
<img id="name" class="class1 class2" src="/test.png" alt="test">
 

包含

為了方便代碼復用,pug提供了include包含功能,以下代碼會將_partial目錄下的head.pug文件內容包含到當前調用的位置。有點C/C++中內聯函數的意思。

doctype html
html(lang='en')
    include _partial/head.pug

繼承

下面是一個簡單的base模板,通過block定義了頁面頭部head和內容body。塊block有點類似C/C++的抽象函數,需要在繼承者中完成定義,填充具體內容。

//- base.pug
html
    head
        block title
    body
        block content

以下文件使用extends繼承以上模板,通過block覆蓋或替換原有塊block。當然,繼承者也可以在原有基礎上繼續擴展。

//- index.pug
extends base.pug

block title
    title "Test title"

block content
    h1 Hello world!
    block article

定義變量

pug中通過- var name = value的形式定義變量

- var intData = 100
- var boolData = false
- var stringData = 'Test'
p.int= intData
p.bool= boolData
p.stringData= stringData

需注意的是,在引用變量時,需要在引用位置加上=號,否則會默認將變量名當成普通字符串使用。

如果想要將變量與其它字符串常量或是變量連接在一起,就不能用等號了,而是應該用#{},該符號會對大括號內的變量進行求值和轉義,最終得到渲染輸出的內容。

- var girl = 'Lily'
- var boy = 'Jack'
p #{girl} is so beautiful!
p And #{boy} is handsome.

條件結構

pug的條件語句與其它語言類似,均是如下這般:

- var A = {value: 'Test'}
- var B = true
if A.value
    p= A.value
else if B
    p= B
else
    p nothing

迭代

pug中使用eachwhile實現循環迭代,each可以返回當前所在項的索引值,默認從0開始計數。

//- each
ol
    each item in ['Sun', 'Mon', 'Tus', 'Wen', 'Thu', 'Fri', 'Sat']
        li= item

//- get index of each
- var week = ['Sun', 'Mon', 'Tus', 'Wen', 'Thu', 'Fri', 'Sat']
ol
    each item, index in week
        li= index + ':' + item

<ol>
  <li>Sun</li>
  <li>Mon</li>
  <li>Tus</li>
  <li>Wen</li>
  <li>Thu</li>
  <li>Fri</li>
  <li>Sat</li>
</ol>
<ol>
  <li>0:Sun</li>
  <li>1:Mon</li>
  <li>2:Tus</li>
  <li>3:Wen</li>
  <li>4:Thu</li>
  <li>5:Fri</li>
  <li>6:Sat</li>
</ol>

while調用方式如下:

//- while
- var day = 1
ul
    while day < 7
        li= day++

Minix

mixin名曰混入,類似其它編程語言中的函數,也是為了代碼復用,可帶參數或不帶參數,定義方式如下:

mixin menu-item(href, name)
    li
        span.dot ●
        a(href=href)= name

其中,menu-item為調用時所用名稱,可認為是函數名,hrefname是參數。同上定義變量所說,a(href=href)= name中第二個=是為了將后面的name當作參數來處理,而不是當作字符串"name"來處理。

調用mixin定義的代碼塊,需通過+號緊跟mixin名稱及參數:

+menu-item('/Archives','Archives')
+menu-item('/About','About')

mixin之所以稱為混入,是因為其語法不局限於函數調用,在mixin可以使用塊block

mixin print(post)
    if block
        block
    else
        p= post

+print("no block")
+print("")
    div.box
        p this is the content of block

<p>no block</p>
<div class="box"><p>this is the content of block</p></div>

JavaScript

注意以下pug語句中第一行的.號。

script(type='text/javascript').
    var data = "Test"
    var enable = true
    if enable
        console.log(data)
    else
        console.log('nothing')

<script type='text/javascript'>
    var data = "Test"
    var enable = true
    if enable
        console.log(data)
    else
        console.log('nothing')
</script>

對於簡單腳本,使用pug尚可,復雜的還是單獨寫到.js文件中,然后通過pug引用方便一些,引用方式如下:

script(type='text/javascript', src='/path/to/js')

//- with hexo function url_for
script(type='text/javascript', src=url_for(theme.js) + '/ready.js')

hexo 相關

hexo主題中使用pug時,可以通過使用hexo提供的全局變量configtheme來分別調用博客根目錄下_config.yml文件中的參數以及主題根目錄下_config.yml文件中的參數。

//- blog config
p= config.description

//- theme config
p= theme.title

 


復制代碼

當然,pug中可以直接使用hexo提供的其它全局變量及輔助函數,使用方法詳見hexo文檔

示例

//- head.pug
head
    meta(http-equiv='content-type', content='text/html; charset=utf-8')
    meta(content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0', name='viewport')
    meta(content='yes', name='apple-mobile-web-app-capable')
    meta(content='black-translucent', name='apple-mobile-web-app-status-bar-style')
    meta(content='telephone=no', name='format-detection')
    meta(name='description', content=config.description)
    block title
    link(rel='stylesheet', type='text/css', href=url_for(theme.css) + '/style.css' + '?v=' + theme.version)
    link(rel='Shortcut Icon', type='image/x-icon', href=url_for('favicon.png'))
    script(type='text/javascript', src='//cdn.bootcss.com/jquery/3.3.1/jquery.min.js')
    block more
//- base.pug
doctype html
html(lang='en')
    include _partial/head.pug
    block more
        link(rel='stylesheet', type='text/css', href=url_for(theme.plugins) + '/prettify/doxy.css')
        script(type='text/javascript', src=url_for(theme.js) + '/ready.js' + '?v=' + theme.version, async)
    
    //- body
    body: #container.box
        .h-wrapper
            include _partial/nav-menu.pug
        // article content
        block content

        include _partial/footer.pug

其中:

  • theme.*為主題配置文件_config.yml中的參數
  • url_forhexo提供的用於查找資源路徑的函數

總結

pug提供了包含,繼承,Mixin等多種方式用於代碼復用,語法簡潔易懂,除了初學時需花費一些時間學習各種標點符號的含義外,其它倒也沒有太大困難。

當然啦,pug還有許多其它特性,但就我目前使用情況而言,以上這些便已足夠。

參考

轉自掘金,原作者litreily,鏈接:https://juejin.im/post/5b8aa21251882542b60ebe80


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM