NodeJS簡易博客系統(二)Swig模板引擎入門

移動終端總決賽終於在昨天在西安電子科技大學結束了,很遺憾咱們沒能取得一個好的成績。說多都是淚,仍是接着學習NodeJs吧,下面是我學習Swing模板引擎的總結。css

1、經常使用

一、變量

{{ foo.bar }}html

{{ foo['bar'] }}json

foo是後臺傳給模板的變量名,bar是foo的屬性值。若是變量未定義,輸出空字符。api

固然,變量也能夠經過過濾器來修改:數組

{{ name|title }} was born on {{ birthday|date('F jS, Y') }}less

// Jane was born on July 6th, 1985函數

二、註釋

註釋使用 括號-# 的語法:oop

{#學習

This is a comment.ui

It will be fully stripped and ignored during parsing.

#}

三、空白

模板裏的空白在最終輸出時默認保留,若是須要去掉空白,能夠在邏輯標籤先後加上空白控制符-:

// seq = [1, 2, 3, 4, 5] 
{% for item in seq -%}   
{{ item }} 
{%- endfor %}
// => 12345

2、模板繼承

Swig 使用 extends 和 block 來實現模板繼承 layout.html

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>{% block title %}My Site{% endblock %}</title>
  {% block head %}
  <link rel="stylesheet" href="main.css">
  {% endblock %}
</head>
<body>
  {% block content %}{% endblock %}
</body>
</html>

index.html

{% extends 'layout.html' %}

{% block title %}My Page{% endblock %}

{% block head %}
  {% parent %}
  <link rel="stylesheet" href="custom.css">
{% endblock %}

{% block content %}
<p>This is just an awesome page.</p>
{% endblock %}

3、變量過濾器

用於修改變量。變量名稱後用 | 字符分隔添加過濾器。您能夠添加多個過濾器。

一、例子

{{ name|title }} was born on {{ birthday|date('F jS, Y') }}
and has {{ bikes|length|default("zero") }} bikes.

也可使用 filter 標籤來爲塊內容添加過濾器

{% filter upper %}oh hi, paul{% endfilter %}

二、內置過濾器

  • add(value):使變量與value相加,能夠轉換爲數值字符串會自動轉換爲數值。
  • addslashes:用 \ 轉義字符串
  • capitalize:大寫首字母
  • date(format[, tzOffset]):轉換日期爲指定格式
  • format:格式
  • tzOffset:時區
  • default(value):默認值(若是變量爲undefined,null,false)
  • escape([type]):轉義字符
    • 默認: &, <, >, ", '
    • js: &, <, >, ", ', =, -, ;
  • first:返回數組第一個值
  • join(glue):同[].join
  • json_encode([indent]):相似JSON.stringify, indent爲縮進空格數
  • last:返回數組最後一個值
  • length:返回變量的length,若是是object,返回key的數量
  • lower:同''.toLowerCase()
  • raw:指定輸入不會被轉義
  • replace(search, replace[, flags]):同''.replace
  • reverse:翻轉數組
  • striptags:去除html/xml標籤
  • title:大寫首字母
  • uniq:數組去重
  • upper:同''.toUpperCase
  • url_encode:同encodeURIComponent
  • url_decode:同decodeURIComponemt

三、自定義過濾器

建立一個 myfilter.js 而後引入到 Swig 的初始化函數中

swig.init({ filters: require('myfilters') });

在 myfilter.js 裏,每個 filter 方法都是一個簡單的 js 方法,下例是一個翻轉字符串的 filter:

exports.myfilter = function (input) {

    return input.toString().split('').reverse().join('');

};

你的 filter 一旦被引入,你就能夠向下面同樣使用:

{{ name|myfilter }}

     {% filter myfilter %}

    I shall be filtered

{% endfilter %}

你也能夠像下面同樣給 filter 傳參數:

exports.prefix = function(input, prefix) {

    return prefix.toString() + input.toString();

};

{{ name|prefix('my prefix') }}

{% filter prefix 'my prefix' %I will be prefixed with "my prefix".{% endfilter %}

{% filter prefix foo %}I will be prefixed with the value stored to `foo`.{% endfilter %}

4、標籤

一、內置標籤

extends:使當前模板繼承父模板,必須在文件最前

  • 參數file:父模板相對模板 root 的相對路徑 block:定義一個塊,使之能夠被繼承的模板重寫,或者重寫父模板的同名塊
  • 參數name:塊的名字,必須以字母數字下劃線開頭 parent:將父模板中同名塊注入當前塊中 include:包含一個模板到當前位置,這個模板將使用當前上下文
  • 參數file: 包含模板相對模板 root 的相對路徑
  • 參數ignore missing:包含模板不存在也不會報錯
  • 參數with x:設置 x 至根上下文對象以傳遞給模板生成。必須是一個鍵值對
  • 參數only:限制模板上下文中用 with x 定義的參數

{% include template_path %}

{% include "path/to/template.js" %}

你能夠標記 ignore missing,這樣若是模板不存在,也不會拋出錯誤

{% include "foobar.html" ignore missing %}

本地聲明的上下文變量,默認狀況不會傳遞給包含的模板。例如如下狀況,inc.html 沒法獲得 foo 和 bar

{% set foo = "bar" %}

{% include "inc.html" %}

{% for bar in thing %}

    {% include "inc.html" %}

{% endfor %}

若是想把本地聲明的變量引入到包含的模板種,可使用 with 參數來把後面的對象建立到包含模板的上下文中

{% set foo = { bar: "baz" } %}

{% include "inc.html" with foo %}

{% for bar in thing %}

    {% include "inc.html" with bar %}

{% endfor %}

若是當前上下文中 foo 和 bar 可用,下面的狀況中,只有 foo 會被 inc.html 定義

{% include "inc.html" with foo only %}

only 必須做爲最後一個參數,放在其餘位置會被忽略

raw:中止解析標記中任何內容,全部內容都將輸出

  • 參數file: 父模板相對模板 root 的相對路徑 for:遍歷對象和數組
  • 參數x:當前循環迭代名
  • 參數in:語法標記
  • 參數y:可迭代對象。可使用過濾器修改

{% for x in y %}

    {% if loop.first %}<ul>{% endif %}

        <li>{{ loop.index }} - {{ loop.key }}: {{ x }}</li>

    {% if loop.last %}</ul>{% endif %}

{% endfor %}

特殊循環變量

  • loop.index:當前循環的索引(1開始)
  • loop.index0:當前循環的索引(0開始)
  • loop.revindex:當前循環從結尾開始的索引(1開始)
  • loop.revindex0:當前循環從結尾開始的索引(0開始)
  • loop.key:若是迭代是對象,是當前循環的鍵,不然同 loop.index
  • loop.first:若是是第一個值返回 true
  • loop.last:若是是最後一個值返回 true
  • loop.cycle:一個幫助函數,以指定的參數做爲週期 ```

 

{% for item in items %}

    <li class="{{ loop.cycle('odd', 'even') }}">{{ item }}</li>

{% endfor %}

在 for 標籤裏使用 else

{% for person in people %}

    {{ person }}

{% else %}

    There are no people yet!

{% endfor %}

if:條件語句

  • 參數:接受任何有效的 JavaScript 條件語句,以及一些其餘人類可讀語法

{% if x %}{% endif %}

{% if !x %}{% endif %}

{% if not x %}{% endif %}

{% if x and y %}{% endif %}

{% if x && y %}{% endif %}

{% if x or y %}{% endif %}

{% if x || y %}{% endif %}

{% if x || (y && z) %}{% endif %}

{% if x [operator] y %}

    Operators: ==, !=, <, <=, >, >=, ===, !==

{% endif %}

{% if x == 'five' %}

    The operands can be also be string or number literals

{% endif %}

{% if x|length === 3 %}

    You can use filters on any operand in the statement.

{% endif %}

{% if x in y %}

    If x is a value that is present in y, this will return true.

{% endif %}

else 和 else if

{% if foo %}

    Some content.

{% else if "foo" in bar %}

    Content if the array `bar` has "foo" in it.

{% else %}

    Fallback content.

{% endif %}

autoescape:改變當前變量的自動轉義行爲

  • 參數on:當前內容是否轉義
  • 參數type:轉義類型,js 或者 html,默認 html

假設

some_html_output = '<p>Hello "you" & \'them\'</p>';

而後

{% autoescape false %}

    {{ some_html_output }}

{% endautoescape %}

{% autoescape true %}

    {{ some_html_output }}

{% endautoescape %}

{% autoescape true "js" %}

    {{ some_html_output }}

{% endautoescape %}

將會輸出

<p>Hello "you" & 'them'</p>

 <p>Hello "you" & 'them' </p>

 \u003Cp\u003EHello \u0022you\u0022 & \u0027them\u0027\u003C\u005Cp\u003E

set:設置一個變量,在當前上下文中複用

  • 參數name:變量名
  • 參數=:語法標記
  • 參數value:變量值

{% set foo = [0, 1, 2, 3, 4, 5] %} {% for num in foo %}

    <li>{{ num }}</li>

{% endfor %}

macro:建立自定義可服用的代碼段

  • 參數...: 用戶定義

{% macro input type name id label value error %}

 <label for="{{ name }}">{{ label }}</label>

 <input type="{{ type }}" name="{{ name }}" id="{{ id }}" value="{{ value }}"{% if error %} class="error"{% endif %}>

{% endmacro %}

而後像下面使用

<div>

    {{ input("text", "fname", "fname", "First Name", fname.value, fname.errors) }}</div><div>

    {{ input("text", "lname", "lname", "Last Name", lname.value, lname.errors) }}</div>

輸出以下

<div>

    <label for="fname">First Name</label>

    <input type="text" name="fname" id="fname" value="Paul"></div><div>

    <label for="lname">Last Name</label>

    <input type="text" name="lname" id="lname" value="" class="error"></div>

import:容許引入另外一個模板的宏進入當前上下文

  • 參數file:引入模板相對模板 root 的相對路徑
  • 參數as:語法標記 var: 分配給宏的可訪問上下文對象

{% import 'formmacros.html' as form %}

{# this will run the input macro #}

    {{ form.input("text", "name") }}

    {# this, however, will NOT output anything because the macro is scoped to the "form"     object: #}

{{ input("text", "name") }}

filter:對整個塊應用過濾器

  • 參數filter_name: 過濾器名字
  • 參數... : 若干傳給過濾器的參數 父模板相對模板 root 的相對路徑

{% filter uppercase %}

    oh hi, {{ name }}

{% endfilter %}

{% filter replace "." "!" "g" %}

    Hi. My name is Paul.

{% endfilter %}

輸出

OH HI, PAUL Hi! My name is Paul!

spaceless:嘗試移除html標籤間的空格

{% spaceless %}

    {% for num in foo %}

        <li>{{ loop.index }}</li>

    {% endfor %}

{% endspaceless %}

輸出

<li>1</li><li>2</li><li>3</li>