koa-swig
引入庫app.js
var render = require('koa-swig');
模版設置app.js
app.context.render = co.wrap(render({ root: __dirname + '/views', autoescape: true, cache: 'memory', // disable, set to false ext: 'html' }));
在another.js調用
router.get('/', function *(next) { console.log(this); yield this.render('index', { title: 'Hello World' }); });
這樣就可以顯示views/index.html了,后面的title設置的參數
前台頁面的渲染
一. 繼承layout.html頁面的內容
index.html頁面代碼
{% extends 'layout.html' %}
{% block title %} {{title}} {% endblock%}
{% block cotent %} <p> 測試</p> {% endblock %}
layout.html頁面代碼
<!doctype html> <html> <head> <meta charset="utf-8"> <meta content="中文"> <title>{% block title %}My Site{% endblock %}</title> </head> <body> {% block content %}{% endblock %} </body> </html>
index.html頁面中的 block title 的內容會填入layout.html頁面的block title中
二.也可以在頁面中引入其它的頁面
{% include "login.html" %}
你可以標記 ignore missing,這樣如果模板不存在,也不會拋出錯誤
{% include "foobar.html" ignore missing %}
如果想把本地聲明的變量引入到包含的模板種,可以使用 with 參數來把后面的對象創建到包含模板的上下文中
{% set foo = { bar: "baz" } %} {% include "inc.html" with foo %} {% for bar in thing %} {% include "inc.html" with bar %} {% endfor %}
三、變量過濾器
1.demo
{{ 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 %}
四、條件語句
{% 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 標簽里使用 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 %}
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") }}
spaceless:嘗試移除html標簽間的空格
{% spaceless %} {% for num in foo %} <li>{{ loop.index }}</li> {% endfor %} {% endspaceless %}
參考:http://www.iqianduan.net/blog/how_to_use_swig