1. 程式人生 > >NodeJS簡易部落格系統(二)Swig模板引擎入門

NodeJS簡易部落格系統(二)Swig模板引擎入門

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

一、常用

1、變數

{{ foo.bar }}

{{ foo['bar'] }}

foo是後臺傳給模板的變數名,bar是foo的屬性值。如果變數未定義,輸出空字元。

當然,變數也可以通過過濾器來修改:

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

// Jane was born on July 6th, 1985

2、註釋

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

{#

This is a comment.

It will be fully stripped and ignored during parsing.

#}

3、空白

模板裡的空白在最終輸出時預設保留,如果需要去掉空白,可以在邏輯標籤前後加上空白控制符-:

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

二、模板繼承

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 %}

三、變數過濾器

用於修改變數。變數名稱後用 | 字元分隔新增過濾器。您可以新增多個過濾器。

1、例子

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

也可以使用 filter 標籤來為塊內容新增過濾器

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

2、內建過濾器

  • 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

3、自定義過濾器

建立一個 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 %}

四、標籤

1、內建標籤

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>