如何使用

API

  1. swig.init({
  2. allowErrors: false,
  3. autoescape: true,
  4. cache: true,
  5. encoding: 'utf8',
  6. filters: {},
  7. root: '/',
  8. tags: {},
  9. extensions: {},
  10. tzOffset: 0
  11. });

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
添加第三方库,可以在编译模板时使用,参见参见自定义标签指南。

nodejs

  1. var tpl = swig.compileFile("path/to/template/file.html");
  2. var renderedHtml = tpl.render({ vars: 'to be inserted in template' });

or

  1. var tpl = swig.compile("Template string here");
  2. var renderedHtml = tpl({ vars: 'to be inserted in template' });

结合Express

  1. npm install express
  2. npm install consolidate

然后

  1. app.engine('.html', cons.swig);
  2. app.set('view engine', 'html');

浏览器

Swig浏览器版本的api基本与nodejs版相同,不同点如下:

  1. 不能使用swig.compileFile,浏览器没有文件系统
  2. 你必须提前使用swig.compile编译好模板
  3. 按顺序使用extends, import, and include,同时在swig.compile里使用参数templateKey来查找模板

    1. var template = swig.compile('<p>{% block content %}{% endblock %}</p>', { filename: 'main' });
    2. var mypage = swig.compile('{% extends "main" %}{% block content %}Oh hey there!{% endblock %}', { filename: 'mypage' });

基础

变量

  1. {{ foo.bar }}
  2. {{ foo['bar'] }}

如果变量未定义,输出空字符。

变量可以通过过滤器来修改:

  1. {{ name|title }} was born on {{ birthday|date('F jS, Y') }}
  2. // Jane was born on July 6th, 1985

逻辑标签

参见标签部分。

注释

空白

模板里的空白在最终输出时默认保留,如果需要去掉空白,可以在逻辑标签前后加上空白控制服-:

  1. {% for item in seq -%}
  2. {{ item }}
  3. {%- endfor %}

模板继承

Swig 使用 extends 和 block 来实现模板继承

layout.html

  1. <!doctype html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>{% block title %}My Site{% endblock %}</title>
  6. {% block head %}
  7. <link rel="stylesheet" href="main.css">
  8. {% endblock %}
  9. </head>
  10. <body>
  11. {% block content %}{% endblock %}
  12. </body>
  13. </html>

index.html

  1. {% extends 'layout.html' %}
  2. {% block title %}My Page{% endblock %}
  3. {% block head %}
  4. {% parent %}
  5. <link rel="stylesheet" href="custom.css">
  6. {% endblock %}
  7. {% block content %}
  8. <p>This is just an awesome page.</p>
  9. {% endblock %}

变量过滤器

用于修改变量。变量名称后用 | 字符分隔添加过滤器。您可以添加多个过滤器。

例子

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

也可以使用 filter 标签来为块内容添加过滤器

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

内置过滤器

add(value)
使变量与value相加,可以转换为数值字符串会自动转换为数值。

addslashes
用 \ 转义字符串

capitalize
大写首字母

date(format[, tzOffset])
转换日期为指定格式

format: 格式
tzOffset: 时区

default(value)
默认值(如果变量为undefined,null,false)

e
同escape

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 的初始化函数中

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

在 myfilter.js 里,每一个 filter 方法都是一个简单的 js 方法,下例是一个翻转字符串的 filter:

  1. exports.myfilter = function (input) {
  2. return input.toString().split('').reverse().join('');
  3. };

你的 filter 一旦被引入,你就可以向下面一样使用:

  1. {{ name|myfilter }}
  2. {% filter myfilter %}I shall be filtered{% endfilter %}

你也可以像下面一样给 filter 传参数:

  1. exports.prefix = function(input, prefix) {
  2. return prefix.toString() + input.toString();
  3. };
  4. {{ name|prefix('my prefix') }}
  5. {% filter prefix 'my prefix' %}I will be prefixed with "my prefix".{% endfilter %}
  6. {% filter prefix foo %}I will be prefixed with the value stored to `foo`.{% endfilter %}

标签

内置标签

extends
使当前模板继承父模板,必须在文件最前

参数:
file:
父模板相对模板 root 的相对路径

block
定义一个块,使之可以被继承的模板重写,或者重写父模板的同名块

参数:
name:
块的名字,必须以字母数字下划线开头

parent
将父模板中同名块注入当前块中

include
包含一个模板到当前位置,这个模板将使用当前上下文

参数:
file:
包含模板相对模板 root 的相对路径
ignore missing:
包含模板不存在也不会报错
with x:
设置 x 至根上下文对象以传递给模板生成。必须是一个键值对
only:
限制模板上下文中用 with x 定义的参数

  1. {% include template_path %}
  2. {% include "path/to/template.js" %}

你可以标记 ignore missing,这样如果模板不存在,也不会抛出错误

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

本地声明的上下文变量,默认情况不会传递给包含的模板。例如以下情况,inc.html 无法得到 foo 和 bar

  1. {% set foo = "bar" %}
  2. {% include "inc.html" %}
  3. {% for bar in thing %}
  4. {% include "inc.html" %}
  5. {% endfor %}

如果想把本地声明的变量引入到包含的模板种,可以使用 with 参数来把后面的对象创建到包含模板的上下文中

  1. {% set foo = { bar: "baz" } %}
  2. {% include "inc.html" with foo %}
  3. {% for bar in thing %}
  4. {% include "inc.html" with bar %}
  5. {% endfor %}

如果当前上下文中 foo 和 bar 可用,下面的情况中,只有 foo 会被 inc.html 定义

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

only 必须作为最后一个参数,放在其他位置会被忽略

raw
停止解析标记中任何内容,所有内容都将输出

参数:
file:
父模板相对模板 root 的相对路径

for
遍历对象和数组

参数:
x:
当前循环迭代名
in:
语法标记
y:
可迭代对象。可以使用过滤器修改

  1. {% for x in y %}
  2. {% if loop.first %}<ul>{% endif %}
  3. <li>{{ loop.index }} - {{ loop.key }}: {{ x }}</li>
  4. {% if loop.last %}</ul>{% endif %}
  5. {% 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:一个帮助函数,以指定的参数作为周期

  1. {% for item in items %}
  2. <li class="{{ loop.cycle('odd', 'even') }}">{{ item }}</li>
  3. {% endfor %}

在 for 标签里使用 else

  1. {% for person in people %}
  2. {{ person }}
  3. {% else %}
  4. There are no people yet!
  5. {% endfor %}

if
条件语句

参数:
...:
接受任何有效的 JavaScript 条件语句,以及一些其他人类可读语法

  1. {% if x %}{% endif %}
  2. {% if !x %}{% endif %}
  3. {% if not x %}{% endif %}
  4. {% if x and y %}{% endif %}
  5. {% if x && y %}{% endif %}
  6. {% if x or y %}{% endif %}
  7. {% if x || y %}{% endif %}
  8. {% if x || (y && z) %}{% endif %}
  9. {% if x [operator] y %}
  10. Operators: ==, !=, <, <=, >, >=, ===, !==
  11. {% endif %}
  12. {% if x == 'five' %}
  13. The operands can be also be string or number literals
  14. {% endif %}
  15. {% if x|length === 3 %}
  16. You can use filters on any operand in the statement.
  17. {% endif %}
  18. {% if x in y %}
  19. If x is a value that is present in y, this will return true.
  20. {% endif %}

else 和 else if

  1. {% if foo %}
  2. Some content.
  3. {% else if "foo" in bar %}
  4. Content if the array `bar` has "foo" in it.
  5. {% else %}
  6. Fallback content.
  7. {% endif %}

autoescape
改变当前变量的自动转义行为

参数:
on:
当前内容是否转义
type:
转义类型,js 或者 html,默认 html

假设

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

然后

  1. {% autoescape false %}
  2. {{ some_html_output }}
  3. {% endautoescape %}
  4. {% autoescape true %}
  5. {{ some_html_output }}
  6. {% endautoescape %}
  7. {% autoescape true "js" %}
  8. {{ some_html_output }}
  9. {% endautoescape %}

将会输出

  1. <p>Hello "you" & 'them'</p>
  2. &lt;p&gt;Hello &quot;you&quot; &amp; 'them' &lt;/p&gt;
  3. \u003Cp\u003EHello \u0022you\u0022 & \u0027them\u0027\u003C\u005Cp\u003E

set
设置一个变量,在当前上下文中复用

参数:
name:
变量名
=:
语法标记
value:
变量值

  1. {% set foo = [0, 1, 2, 3, 4, 5] %}
  2. {% for num in foo %}
  3. <li>{{ num }}</li>
  4. {% endfor %}

macro
创建自定义可服用的代码段

参数:
...:
用户定义

  1. {% macro input type name id label value error %}
  2. <label for="{{ name }}">{{ label }}</label>
  3. <input type="{{ type }}" name="{{ name }}" id="{{ id }}" value="{{ value }}"{% if error %} class="error"{% endif %}>
  4. {% endmacro %}

然后像下面使用

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

输出如下

  1. <div>
  2. <label for="fname">First Name</label>
  3. <input type="text" name="fname" id="fname" value="Paul">
  4. </div>
  5. <div>
  6. <label for="lname">Last Name</label>
  7. <input type="text" name="lname" id="lname" value="" class="error">
  8. </div>

import
允许引入另一个模板的宏进入当前上下文

参数:
file:
引入模板相对模板 root 的相对路径
as:
语法标记
var:
分配给宏的可访问上下文对象

  1. {% import 'formmacros.html' as form %}
  2. {# this will run the input macro #}
  3. {{ form.input("text", "name") }}
  4. {# this, however, will NOT output anything because the macro is scoped to the "form" object: #}
  5. {{ input("text", "name") }}

filter
对整个块应用过滤器

参数:
filter_name:
过滤器名字
... :
若干传给过滤器的参数
父模板相对模板 root 的相对路径

  1. {% filter uppercase %}oh hi, {{ name }}{% endfilter %}
  2. {% filter replace "." "!" "g" %}Hi. My name is Paul.{% endfilter %}

输出

  1. OH HI, PAUL
  2. Hi! My name is Paul!

spaceless
尝试移除html标签间的空格

  1. {% spaceless %}
  2. {% for num in foo %}
  3. <li>{{ loop.index }}</li>
  4. {% endfor %}
  5. {% endspaceless %}

输出

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

Swig 使用指南的更多相关文章

  1. 【转】Swig 使用指南

    原文链接:https://www.cnblogs.com/elementstorm/p/3142644.html 如何使用 API swig.init({ allowErrors: false, au ...

  2. 【转】Swig使用指南

    如何使用 API swig.init({ allowErrors: false, autoescape: true, cache: true, encoding: 'utf8', filters: { ...

  3. Swig 使用指南 (express模板)

    如何使用 API swig.init({ allowErrors: false, autoescape: true, cache: true, encoding: 'utf8', filters: { ...

  4. swig模板引擎汇总

    1. Express中使用swig模板引擎 2.Swig 使用指南 3.jade to html online

  5. Python - SIP参考指南 - 介绍

    介绍 本文是SIP4.18的参考指南.SIP是一种Python工具,用于自动生成Python与C.C++库的绑定.SIP最初是在1998年用PyQt开发的,用于Python与Qt GUI toolki ...

  6. javaCV入门指南:调用FFmpeg原生API和JavaCV是如何封装了FFmpeg的音视频操作?

    通过"javaCV入门指南:序章 "大家知道了处理音视频流媒体的前置基本知识,基本知识包含了像素格式.编解码格式.封装格式.网络协议以及一些音视频专业名词,专业名词不会赘述,自行搜 ...

  7. SWIG 3 中文手册——5. SWIG 基础知识

    目录 5 SWIG 基础知识 5.1 运行 SWIG 5.1.1 输入格式 5.1.2 SWIG 输出 5.1.3 注释 5.1.4 C 预处理器 5.1.5 SWIG 指令 5.1.6 解析限制 5 ...

  8. SWIG 3 中文手册——1. 前言

    目录 1 前言 1.1 引言 1.2 SWIG 版本 1.3 SWIG 许可证 1.4 SWIG 资源 1.5 前提要求 1.6 本手册的组织构成 1.7 如何避免阅读手册 1.8 向后兼容 1.9 ...

  9. 能动手绝不多说:开源评论系统remark42上手指南

    能动手绝不多说:开源评论系统 remark42 上手指南 前言 写博客嘛, 谁不喜欢自己倒腾一下呢. 从自建系统到 Github Page, 从 Jekyll 到 Hexo, 年轻的时候谁不喜欢多折腾 ...

随机推荐

  1. 解决The current branch is not configured for pull No value for key branch.master.merge found in confi

    1.在本地工程目录找到config文件(我的是在E:\rocket\rocket\.git): 2.修改config文件内容为: [core] repositoryformatversion = fi ...

  2. 支持Json进行操作的Javascript类库TAFFY DB

    前段时间工作中用到Json数据,希望将一些简单的增删改查放到客户端来做,这样也能减少服务器端的压力.分别查找了几个可以对Json进行操作的javascript 类库,最终选定了TAFFY DB.原因如 ...

  3. Lambda表达式和表达式树

    在C# 2.0中,通过方法组转换和匿名方法,使委托的实现得到了极大的简化.但是,匿名方法仍然有些臃肿,而且当代码中充满了匿名方法的时候,可读性可能就会受到影响.C# 3.0中出现的Lambda表达式在 ...

  4. Bootstrap3.0学习第十四轮(分页、徽章)

    详情请查看http://aehyok.com/Blog/Detail/21.html 个人网站地址:aehyok.com QQ 技术群号:206058845,验证码为:aehyok 本文文章链接:ht ...

  5. JavaScript基础---AJAX

    内容提纲: 1.XMLHttpRequest 2.GET与POST 3.封装Ajax  发文不易,转载请注明链接出处,谢谢! 2005年Jesse James Garrett发表了一篇文章,标题为:“ ...

  6. Javascript的io操作

    一.功能实现核心:FileSystemObject 对象 要在javascript中实现文件操作功能,主要就是依靠FileSystemobject对象. 二.FileSystemObject编程 使用 ...

  7. chromiun 学习《一》

    众所周知,Chrome是建立在开源的Chromium项目上的. 而且不得不说,学习并分析开源项目的代码对一个程序员的提高确实蛮大的.这篇博文我会记录一下学习过程中我遇到的一些问题,并分享学习中我所参考 ...

  8. Daily Scrum – 1/12

    Meeting Minutes Merge Wordlist & Word Recite entry. (P0) – Done. Remove "Word Challenge&quo ...

  9. Java算法-hash算法

    Hash ,一般翻译做“ 散列” ,也有直接音译为“ 哈希” 的,就是把任意长度的输入(又叫做预映射, pre-image ),通过散列算法,变换成固定长度的输出,该输出就是散列值.这种转换是一种压缩 ...

  10. 【前端】less学习

    Less 是什么? Less is more,than CSS. Less就是搞笑高效编写和维护CSS的一种语法. 1.下载Koala考拉,一款国人编写的less开发器. 2.可以用Sublime T ...