一、如何使用
1、API
swig.init({ allowErrors: false, autoescape: true, cache: true, encoding: 'utf8', filters: {}, root: '/', tags: {}, extensions: {}, tzOffset: 0 });
options:
- allowErrors: 默認值為 false。將所有模板解析和編譯錯誤直接輸出到模板。如果為 true,則將引發錯誤,拋出到 Node.js 進程中,可能會使您的應用程序崩潰。
- autoescape: 默認true,強烈建議保持。字符轉換表請參閱轉義過濾器。
- true: HTML安全轉義
- false: 不轉義,除非使用轉義過濾器或者轉義標簽
- 'js': js安全轉義
- cache: 更改為 false 將重新編譯每個請求的模板的文件。正式環境建議保持true。
- encoding: 模板文件編碼
- root: 需要搜索模板的目錄。如果模板傳遞給 swig.compileFile 絕對路徑(以/開頭),Swig不會在模板root中搜索。如果傳遞一個數組,使用第一個匹配成功的數組項。
- tzOffset: 設置默認時區偏移量。此設置會使轉換日期過濾器會自動的修正相應時區偏移量。
- filters:自定義過濾器或者重寫默認過濾器,參見自定義過濾器指南。
- tags: 自定義標簽或者重寫默認標簽,參見自定義標簽指南。
- extensions: 添加第三方庫,可以在編譯模板時使用,參見參見自定義標簽指南。
2、nodejs
var tpl = swig.compileFile("path/to/template/file.html"); var renderedHtml = tpl.render({ vars: 'to be inserted in template' });
或者
var tpl = swig.compile("Template string here"); var renderedHtml = tpl({ vars: 'to be inserted in template' });
3、結合Express
npm install express
npm install consolidate
然后
app.engine('.html', cons.swig);
app.set('view engine', 'html');
4、瀏覽器
Swig瀏覽器版本的api基本與nodejs版相同,不同點如下:
- 不能使用swig.compileFile,瀏覽器沒有文件系統
- 你必須提前使用swig.compile編譯好模板
- 按順序使用extends, import, and include,同時在swig.compile里使用參數templateKey來查找模板
var template = swig.compile('<p>{% block content %}{% endblock %}</p>', { filename: 'main' }); var mypage = swig.compile('{% extends "main" %}{% block content %}Oh hey there!{% endblock %}', { filename: 'mypage' });
二、基礎
1、變量
{{ foo.bar }}
{{ foo['bar'] }}
如果變量未定義,輸出空字符。
變量可以通過過濾器來修改:
{{ name|title }} was born on {{ birthday|date('F jS, Y') }} // Jane was born on July 6th, 1985
2、邏輯標簽
參見標簽部分。
3、注釋
4、空白
模板里的空白在最終輸出時默認保留,如果需要去掉空白,可以在邏輯標簽前后加上空白控制服-:
{% for item in seq -%} {{ item }} {%- endfor %}
三、模板繼承
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>