iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 8
2
Modern Web

從零開始遲來的Web開發筆記系列 第 8

HTML模版語言-pug的指令『include』和『繼承』

Pug 的include

首先我們先建立一份base.pug,基於上面敘述,我們可以有兩種寫法,第一種依照Pug的風格:

<!doctype html>

html
  head
    title Title
  body
    include body.pug

第二種寫法,在HTML裡插入:

<!doctype html>
<html>

<head>
    <title>Title</title>
</head>

<body>
    include body.pug
</body>

</html>

Pug給我的感覺非常像是命令型程式語言,每一個關鍵字(keyword)的代表著不同命令。譬如上一篇提到的h1就是生成<h1></h1>標籤,並且支援一些特別的用法,並且加入裡Python裡縮排的特性,依照縮排代表不同階層。但是這次主要提到的是includeextends/block的用法。

include file.pug如同PHP裡的include一樣,是直接讀取檔案,並將內容插入到將對應的位置。以上面例子來說,可以在同樣目錄位置下,在建立一份名爲body.pug的檔案,檔案內容如下:

<header>This is HEADER</header>
<article>This is MAIN</article>
<footer>This is FOOTER</footer>

當然,如果要寫成Pug的形式也可以:

header This is HEADER
article This is MAIN
footer This is FOOTER

就把第一個當成命令,之後是相關參數,這和bash、tcl與perl有點像。不過Pug的寫法在這邊顯示起來有點難看哈哈。

在經過pug entry.pug -o public/以後,應該可以在public的資料夾底下看到entry.html文件,並且內容已經變成是*(可能不太好看,如果需要美化輸出,可以在pug轉換時,加上--pretty的參數)*:

<!doctype html>
<html>

<head>
    <title>Title</title>
</head>

<body>
    <header>This is HEADER</header>
    <article>This is MAIN</article>
    <footer>This is FOOTER</footer>
</body>

</html>

Pug 的 extends/block

再來說說Pug中繼承的部分。沒錯HTML也可以有類似物件導向(OOP)的繼承,這部分是我覺得非常有趣且有用的部分,也難怪我朋友我有此言(見上篇)。先來建立一份父HPug文件,名爲base.pug:

<!doctype html>
<html>

<head>
    block title
        <title>Title</title>
</head>

<body>
    block header
        <header>This is HEADER</header>
    block body
        <article>This is MAIN</article>
    block footer
        <footer>This is FOOTER</footer>
</body>

</html>

對....和上面很像,就是多了block。每一個block代表著可以被覆寫(Overwrite)的部分,並有一個block的名稱作爲標示。這有點像OOP裡類別的虛擬方法(virtual method),或是其他可以被繼承覆寫的方法,並且帶有函式名稱與參數個數和參數型別。(特別注意縮排存在影響)

再來是子Pug文件,也叫作entry.pug好了:
首先先繼承base.pug

extends base.pug

在來改寫各個部分,譬如header我想改成:

block header
    <header>Oh, This is Child Header</header>

我想應該不難理解,所以整份文件會如下:

extends base.pug

block header
    <header>Oh, This is Child Header</header>

block append body
    <article>This is Child Body</article>

block prepend footer
    <div>Before footer, Child want to say somthing</div>

怎麼樣?更能專注於某一區塊了吧!不過上面有些東西還沒提到,extendsblock直接覆寫的部分已經結束,不過除了覆寫,還可以做插入。如果想要在原本內容之後插入,就在加上append;而在之前,就多加上prepend。其實覆寫也可以寫成block replace block_id,也就是多加上replace

我們來看看最後使用pug entry.pug -o public/轉換生成的結果吧~

<!doctype html>
<html>

<head>
    <title>Title</title>
</head>

<body>
    <!-- direct replace -->
    <header>Oh, This is Child Header</header>

    <!-- append -->
    <article>This is MAIN</article>
    <article>This is Child Body</article>

    <!-- prepend -->
    <div>Before footer, Child want to say somthing</div>
    <footer>This is FOOTER</footer>
</body>

</html>

上一篇
HTML模版語言-pug介紹與安裝
下一篇
我知道的Node.js那點小事
系列文
從零開始遲來的Web開發筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言