nodejs模板引擎——koa-swig

引入庫(kù)app.js
const Koa = require('koa')
const Router = require('koa-router')
const render = require('koa-swig');
const co = require('co');
const app = new Koa();
const router = new Router();
設(shè)置app.js
app.context.render = co.wrap(render({
  root: __dirname + '/views',
  autoescape: true,
  cache: 'memory', // disable, set to false 
  ext: 'html'
}));
app.use(async ctx => ctx.body = await ctx.render('index'));
app.listen(2333);

前臺(tái)頁面的渲染

一. 繼承l(wèi)ayout.html頁面的內(nèi)容

index.html頁面代碼

{% extends 'layout.html' %}

{% block title %} {{title}} {% endblock%}

{% block cotent %} <p> 測(cè)試</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 的內(nèi)容會(huì)填入layout.html頁面的block title中

二.也可以在頁面中引入其它的頁面

{% include "login.html" %} 

你可以標(biāo)記 ignore missing,這樣如果模板不存在耗绿,也不會(huì)拋出錯(cuò)誤

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

如果想把本地聲明的變量引入到包含的模板種吓妆,可以使用 with 參數(shù)來把后面的對(duì)象創(chuàng)建到包含模板的上下文中

{% 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 標(biāo)簽來為塊內(nèi)容添加過濾器

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

2宣渗、內(nèi)置過濾器

  • add(value):使變量與value相加抖所,可以轉(zhuǎn)換為數(shù)值字符串會(huì)自動(dòng)轉(zhuǎn)換為數(shù)值。
  • addslashes:用 \ 轉(zhuǎn)義字符串
  • capitalize:大寫首字母
  • date(format[, tzOffset]):轉(zhuǎn)換日期為指定格式
  • format:格式
  • tzOffset:時(shí)區(qū)
  • default(value):默認(rèn)值(如果變量為undefined痕囱,null田轧,false)
  • escape([type]):轉(zhuǎn)義字符
    • 默認(rèn): &, <, >, ", '
    • js: &, <, >, ", ', =, -, ;
  • first:返回?cái)?shù)組第一個(gè)值
  • join(glue):同[].join
  • json_encode([indent]):類似JSON.stringify, indent為縮進(jìn)空格數(shù)
  • last:返回?cái)?shù)組最后一個(gè)值
  • length:返回變量的length,如果是object鞍恢,返回key的數(shù)量
  • lower:同''.toLowerCase()
  • raw:指定輸入不會(huì)被轉(zhuǎn)義
  • replace(search, replace[, flags]):同''.replace
  • reverse:翻轉(zhuǎn)數(shù)組
  • striptags:去除html/xml標(biāo)簽
  • title:大寫首字母
  • uniq:數(shù)組去重
  • upper:同''.toUpperCase
  • url_encode:同encodeURIComponent
  • url_decode:同decodeURIComponemt

3傻粘、自定義過濾器

創(chuàng)建一個(gè) myfilter.js 然后引入到 Swig 的初始化函數(shù)中

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

在 myfilter.js 里每窖,每一個(gè) filter 方法都是一個(gè)簡(jiǎn)單的 js 方法,下例是一個(gè)翻轉(zhuǎn)字符串的 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:當(dāng)前循環(huán)的索引(1開始)
loop.index0:當(dāng)前循環(huán)的索引(0開始)
loop.revindex:當(dāng)前循環(huán)從結(jié)尾開始的索引(1開始)
loop.revindex0:當(dāng)前循環(huán)從結(jié)尾開始的索引(0開始)
loop.key:如果迭代是對(duì)象,是當(dāng)前循環(huán)的鍵警绩,否則同 loop.index
loop.first:如果是第一個(gè)值返回 true loop.last:如果是最后一個(gè)值返回 true loop.cycle:一個(gè)幫助函數(shù)崇败,以指定的參數(shù)作為周期 ```

在 for 標(biāo)簽里使用 else

{% for person in people %}
    {{ person }}
{% else %}
    There are no people yet! {% endfor %}

if:條件語句

  • 參數(shù):接受任何有效的 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:改變當(dāng)前變量的自動(dòng)轉(zhuǎn)義行為

  • 參數(shù)on:當(dāng)前內(nèi)容是否轉(zhuǎn)義
  • 參數(shù)type:轉(zhuǎn)義類型肩祥,js 或者 html后室,默認(rèn) html

假設(shè)

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:設(shè)置一個(gè)變量,在當(dāng)前上下文中復(fù)用

  • 參數(shù)name:變量名
  • 參數(shù)=:語法標(biāo)記
  • 參數(shù)value:變量值
{% set foo = [0, 1, 2, 3, 4, 5] %} {% for num in foo %} <li>{{ num }}</li> {% endfor %}

macro:創(chuàng)建自定義可服用的代碼段

  • 參數(shù)...: 用戶定義
{% 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:允許引入另一個(gè)模板的宏進(jìn)入當(dāng)前上下文

  • 參數(shù)file:引入模板相對(duì)模板 root 的相對(duì)路徑
  • 參數(shù)as:語法標(biāo)記 var: 分配給宏的可訪問上下文對(duì)象
{% 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標(biāo)簽間的空格

{% spaceless %}
    {% for num in foo %} <li>{{ loop.index }}</li> {% endfor %}
{% endspaceless %}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末混狠,一起剝皮案震驚了整個(gè)濱河市岸霹,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌将饺,老刑警劉巖贡避,帶你破解...
    沈念sama閱讀 219,490評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異予弧,居然都是意外死亡刮吧,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,581評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門掖蛤,熙熙樓的掌柜王于貴愁眉苦臉地迎上來杀捻,“玉大人,你說我怎么就攤上這事蚓庭≈录ィ” “怎么了?”我有些...
    開封第一講書人閱讀 165,830評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵器赞,是天一觀的道長(zhǎng)垢袱。 經(jīng)常有香客問我,道長(zhǎng)拳魁,這世上最難降的妖魔是什么惶桐? 我笑而不...
    開封第一講書人閱讀 58,957評(píng)論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮潘懊,結(jié)果婚禮上姚糊,老公的妹妹穿的比我還像新娘。我一直安慰自己授舟,他們只是感情好救恨,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,974評(píng)論 6 393
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著释树,像睡著了一般肠槽。 火紅的嫁衣襯著肌膚如雪擎淤。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,754評(píng)論 1 307
  • 那天秸仙,我揣著相機(jī)與錄音嘴拢,去河邊找鬼。 笑死寂纪,一個(gè)胖子當(dāng)著我的面吹牛席吴,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播捞蛋,決...
    沈念sama閱讀 40,464評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼孝冒,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了拟杉?” 一聲冷哼從身側(cè)響起庄涡,我...
    開封第一講書人閱讀 39,357評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎搬设,沒想到半個(gè)月后穴店,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,847評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡拿穴,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,995評(píng)論 3 338
  • 正文 我和宋清朗相戀三年迹鹅,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片贞言。...
    茶點(diǎn)故事閱讀 40,137評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖阀蒂,靈堂內(nèi)的尸體忽然破棺而出该窗,到底是詐尸還是另有隱情,我是刑警寧澤蚤霞,帶...
    沈念sama閱讀 35,819評(píng)論 5 346
  • 正文 年R本政府宣布酗失,位于F島的核電站,受9級(jí)特大地震影響昧绣,放射性物質(zhì)發(fā)生泄漏规肴。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,482評(píng)論 3 331
  • 文/蒙蒙 一夜畴、第九天 我趴在偏房一處隱蔽的房頂上張望拖刃。 院中可真熱鬧,春花似錦贪绘、人聲如沸兑牡。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,023評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽均函。三九已至亿虽,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間苞也,已是汗流浹背洛勉。 一陣腳步聲響...
    開封第一講書人閱讀 33,149評(píng)論 1 272
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留如迟,地道東北人收毫。 一個(gè)月前我還...
    沈念sama閱讀 48,409評(píng)論 3 373
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像氓涣,于是被迫代替她去往敵國(guó)和親牛哺。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,086評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容