Swig

一个适用于Node.js和浏览器的模板引擎

扩展Swig

定制过滤器

过滤器能对输入参数执行转换。

过滤器是在渲染时间执行的,所以不管怎么样它们都不会直接修改编译后的模板结构。

Swig所有的内置过滤器都是以同样的方式编写的。查看更多的栗子,请在Swig源码中参考 `filters.js` 文件。

如需禁止定制过滤器的自动转义,给过滤器方法增加 `safe = true;` 属性即可,这样无论Swig的全局设置是什么,输出都不会被转义。

参数

Name Type Optional Default Description
input * undefined

Input argument, automatically sent from Swig's built-in parser.

args * undefined

All other arguments are defined by the Filter author.

// This filter will return 'bazbop' if the idx on the input is not 'foobar'
swig.setFilter('foobar', function (input, idx) {
  return input[idx] === 'foobar' ? input[idx] : 'bazbop';
});
// myvar = ['foo', 'bar', 'baz', 'bop'];
// => {{ myvar|foobar(3) }}
// Since myvar[3] !== 'foobar', we render:
// => bazbop
// This filter will disable auto-escaping on its output:
function bazbop (input) { return input; }
bazbop.safe = true;
swig.setFilter('bazbop', bazbop);
// => {{ "<p>"|bazbop }}
// => <p>

定制标签

你可以扩展Swig去处理定制标签,这些标签会对模板中的所有块执行相关操作。使用 swig.setTag(name, parse, compile, ends, blockLevel) 来添加你的定制标签。

Swig所有的标签都是使用相同的api(比如 extendsblock)来编写的。阅读标签源码查看更多事例来编写自己的定制标签。

parse(str, line, parser, types, stack, options, swig)

为你的标签定义定制的解析方法。

方法

Name Type Optional Default Description
str string undefined

The full token string of the tag.

line number undefined

The line number that this tag appears on.

parser TokenParser undefined

A TokenParser instance.

types TYPES undefined

Lexer token type enum.

stack TagToken[] undefined

The current stack of open tags.

options SwigOpts undefined

Swig Options Object.

swig object undefined

The Swig instance (gives acces to loaders, parsers, etc)

exports.parse = function (str, line, parser, types, options, swig) {
  parser.on('start', function () {
    // ...
  });
  parser.on(types.STRING, function (token) {
    // ...
  });
};

compile(compiler, args, content, parents, options, blockName)

为VarToken和TagToken对象编译回调。

参数

Name Type Optional Default Description
compiler parserCompiler undefined
args array undefined

Array of parsed arguments on the for the token.

content array undefined

Array of content within the token.

parents array undefined

Array of parent templates for the current template context.

options SwigOpts undefined

Swig Options Object

blockName string undefined

Name of the direct block parent, if any.

exports.compile = function (compiler, args, content, parents, options, blockName) {
  if (args[0] === 'foo') {
    return compiler(content, parents, options, blockName) + '\n';
  }
  return '_output += "fallback";\n';
};

ends

当一个标签在模板中被声明后,控制该标签时是否必须有一个{% end[tagName] %}

exports.ends = true;
// => A template that fails to close this tag will throw an Error.
exports.ends = false;
// => A template attempts close this tag will throw an Error.

blockLevel

当扩展一个父级模板时,允许标签在 {% block <name> %}{% endblock %} 标签外部被重写。

exports.blockLevel = true;
{% extends "foo" %}
{% mytag foo bar baz %}
// Normally this will be ignored, but since we allowed it to be block-level,
// it will be included in the fully-parsed template.

{% block content %}
  ...
{% endblock %}

TYPES

Source: lib/lexer.js#L16

枚举token types.

Value Name Description
'*' For every token, run the given callback.
'start' Run before any token is parsed.
'end' Run after all other tokens have been parsed.
0 types.WHITESPACE

Whitespace

1 types.STRING

Plain string

2 types.FILTER

Variable filter

3 types.FILTEREMPTY

Empty variable filter

4 types.FUNCTION

Function

5 types.FUNCTIONEMPTY

Function with no arguments

6 types.PARENOPEN

Open parenthesis

7 types.PARENCLOSE

Close parenthesis

8 types.COMMA

Comma

9 types.VAR

Variable

10 types.NUMBER

Number

11 types.OPERATOR

Math operator

12 types.BRACKETOPEN

Open square bracket

13 types.BRACKETCLOSE

Close square bracket

14 types.DOTKEY

Key on an object using dot-notation

15 types.ARRAYOPEN

Start of an array

17 types.CURLYOPEN

Open curly brace

18 types.CURLYCLOSE

Close curly brace

19 types.COLON

Colon (:)

20 types.COMPARATOR

JavaScript-valid comparator

21 types.LOGIC

Boolean logic

22 types.NOT

Boolean logic "not"

23 types.BOOL

true or false

24 types.ASSIGNMENT

Variable assignment

25 types.METHODOPEN

Start of a method

100 types.UNKNOWN

Unknown type