网页模板pug基本语法

9,530 阅读6分钟

该博客首发于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还有许多其它特性,但就我目前使用情况而言,以上这些便已足够。

参考