Swig

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

Swig API

Object Type: SwigOpts

Source: lib/swig.js#L17

Swig Options Object.该对象可以传递给大多数API级别(API-level)的swig方法来控制引擎。所有的key值都是可选项。

属性

Name Type Description
autoescape boolean Controls whether or not variable output will automatically be escaped for safe HTML output. Defaults to true. Functions executed in variable statements will not be auto-escaped. Your application/functions should take care of their own auto-escaping.
varControls array Open and close controls for variables. Defaults to ['{{', '}}'].
tagControls array Open and close controls for tags. Defaults to ['{%', '%}'].
cmtControls array Open and close controls for comments. Defaults to ['{#', '#}'].
locals object Default variable context to be passed to all templates.
cache CacheOptions Cache control for templates. Defaults to saving in 'memory'. Send false to disable. Send an object with get and set functions to customize.
loader TemplateLoader The method that Swig will use to load templates. Defaults to swig.loaders.fs.

Object Type: CacheOptions

Source: lib/swig.js#L34

模板缓存控制。Swig默认会将所有的模板都存入内存。

例子

// Default
swig.setDefaults({ cache: 'memory' });
// Disables caching in Swig.
swig.setDefaults({ cache: false });
// Custom cache storage and retrieval
swig.setDefaults({
  cache: {
    get: function (key) { ... },
    set: function (key, val) { ... }
  }
});

Object Type: TemplateLoader

Source: lib/swig.js#L53

可以使用swig.loaders.fsswig.loaders.memory模板加载器来配置Swig,如果想使用自己编写的加载器也是可以的哦!

获取更多信息,请查看模板加载器文档

例子

// Default, FileSystem loader
swig.setDefaults({ loader: swig.loaders.fs() });
// FileSystem loader allowing a base path
// With this, you don't use relative URLs in your template references
swig.setDefaults({ loader: swig.loaders.fs(__dirname + '/templates') });
// Memory Loader
swig.setDefaults({ loader: swig.loaders.memory({
  layout: '{% block foo %}{% endblock %}',
  page1: '{% extends "layout" %}{% block foo %}Tacos!{% endblock %}'
})});

swig.version

Source: lib/swig.js#L15

Swig版本号,字符串类型

例子

if (swig.version === "1.4.2") { ... }

swig.setDefaults( options )

Source: lib/swig.js#L143

设置基本的默认项和Swig环境。

参数

Name Type Optional Default Description
options SwigOpts {} Swig options object.

返回

undefined:

例子

swig.setDefaults({ cache: false });
// => Disables Cache
swig.setDefaults({ locals: { now: function () { return new Date(); } }});
// => sets a globally accessible method for all template
//    contexts, allowing you to print the current date
// => {{ now()|date('F jS, Y') }}

swig.setDefaultTZOffset( offset )

Source: lib/swig.js#L153

通过日期过滤器为格式化日期设置默认的时区。这是一个全局设置,无论对于新的还是旧的Swig环境,都会受到影响。

参数

Name Type Optional Default Description
offset number undefined Offset from GMT, in minutes.

返回

undefined:

swig.Swig( opts )

Source: lib/swig.js#L171

创建一个新的、独立的Swig编译/渲染环境。

参数

Name Type Optional Default Description
opts SwigOpts {} Swig options object.

返回

object: New Swig environment.

例子

var swig = require('swig');
var myswig = new swig.Swig({varControls: ['<%=', '%>']});
myswig.render('Tacos are <%= tacos =>!', { locals: { tacos: 'delicious' }});
// => Tacos are delicious!
swig.render('Tacos are <%= tacos =>!', { locals: { tacos: 'delicious' }});
// => 'Tacos are <%= tacos =>!'

swig.invalidateCache( )

Source: lib/swig.js#L251

清除内存中的模板缓存。

返回

undefined:

例子

swig.invalidateCache();

swig.setFilter( name , method )

Source: lib/swig.js#L270

为swig变量增加一个定制的过滤器。

参数

Name Type Optional Default Description
name string undefined Name of filter, used in templates. Will overwrite previously defined filters, if using the same name.
method function undefined Function that acts against the input. See Custom Filters for more information.

返回

undefined:

例子

function replaceMs(input) { return input.replace(/m/g, 'f'); }
swig.setFilter('replaceMs', replaceMs);
// => {{ "onomatopoeia"|replaceMs }}
// => onofatopeia

swig.setTag( name , parse , compile , ends , blockLevel )

Source: lib/swig.js#L295

增加一个定制的tag。想要使用自己的扩展来编译模板代码,请参看swig.setExtension

获取更详细的编写定制tag的方法,请查看Custom Tags

参数

Name Type Optional Default Description
name string undefined Tag name.
parse function undefined Method for parsing tokens.
compile function undefined Method for compiling renderable output.
ends boolean false Whether or not this tag requires an end tag.
blockLevel boolean false If false, this tag will not be compiled outside of block tags when extending a parent template.

返回

undefined:

例子

var tacotag = require('./tacotag');
swig.setTag('tacos', tacotag.parse, tacotag.compile, tacotag.ends, tacotag.blockLevel);
// => {% tacos %}Make this be tacos.{% endtacos %}
// => Tacos tacos tacos tacos.

swig.setExtension( name , object )

Source: lib/swig.js#L326

为定制标签增加扩展。在模板中允许任何定制标签通过特殊的全局变量对象_ext来获取全局变量方法。

参数

Name Type Optional Default Description
name string undefined Key name of the extension. Accessed via _ext[name].
object * undefined The method, value, or object that should be available via the given name.

返回

undefined:

例子

swig.setExtension('trans', function (v) { return translate(v); });
function compileTrans(compiler, args, content, parent, options) {
  return '_output += _ext.trans(' + args[0] + ');'
};
swig.setTag('trans', parseTrans, compileTrans, true);

swig.precompile( source , options )

Source: lib/swig.js#L485

将一个source string预编译为一个可缓存的模板函数。

参数

Name Type Optional Default Description
source string undefined Swig template source string.
options SwigOpts {} Swig options object.

返回

object: Renderable function and tokens object.

例子

swig.precompile('{{ tacos }}');
// => {
//      tpl: function (_swig, _locals, _filters, _utils, _fn) { ... },
//      tokens: {
//        name: undefined,
//        parent: null,
//        tokens: [...],
//        blocks: {}
//      }
//    }

In order to render a pre-compiled template, you must have access to filters and utils from Swig. <var>efn</var> is simply an empty function that does nothing.

swig.render( source , options )

Source: lib/swig.js#L523

为最后的输出编译、渲染模板字符串。

当渲染一个source string时,需要在设置选项中指定一个文件路径,这样才能使extendsincludeimport 正常运行。通过在options参数中增加{ filename: '/absolute/path/to/mytpl.html' }来实现。

参数

Name Type Optional Default Description
source string undefined Swig template source string.
options SwigOpts {} Swig options object.

返回

string: Rendered output.

例子

swig.render('{{ tacos }}', { locals: { tacos: 'Tacos!!!!' }});
// => Tacos!!!!

swig.renderFile( pathName , locals , cb )

Source: lib/swig.js#L547

为最终的输出编译、渲染模板文件,这对于像Express.js这样的库来说非常有用。

参数

Name Type Optional Default Description
pathName string undefined File location.
locals object {} Template variable context.
cb Function undefined Asyncronous callback function. If not provided, compileFile will run syncronously.

返回

string: Rendered output.

例子

swig.renderFile('./template.html', {}, function (err, output) {
  if (err) {
    throw err;
  }
  console.log(output);
});
swig.renderFile('./template.html', {});
// => output

swig.compile( source , options )

Source: lib/swig.js#L592

将string source编译成一个可渲染的模板函数。

参数

Name Type Optional Default Description
source string undefined Swig template source string.
options SwigOpts {} Swig options object.

返回

function: Renderable function with keys for parent, blocks, and tokens.

例子

var tpl = swig.compile('{{ tacos }}');
// => {
//      [Function: compiled]
//      parent: null,
//      tokens: [{ compile: [Function] }],
//      blocks: {}
//    }
tpl({ tacos: 'Tacos!!!!' });
// => Tacos!!!!

When compiling a source string, a file path should be specified in the options object in order for <var>extends</var>, <var>include</var>, and <var>import</var> to work properly. Do this by adding <code data-language="js">{ filename: '/absolute/path/to/mytpl.html' }</code> to the options argument.

swig.compileFile( pathname , options , cb )

Source: lib/swig.js#L653

将一个source file编译成一个可渲染的模板函数。

参数

Name Type Optional Default Description
pathname string undefined File location.
options SwigOpts {} Swig options object.
cb Function undefined Asyncronous callback function. If not provided, compileFile will run syncronously.

返回

function: Renderable function with keys for parent, blocks, and tokens.

例子

var tpl = swig.compileFile('./mytpl.html');
// => {
//      [Function: compiled]
//      parent: null,
//      tokens: [{ compile: [Function] }],
//      blocks: {}
//    }
tpl({ tacos: 'Tacos!!!!' });
// => Tacos!!!!
swig.compileFile('/myfile.txt', { varControls: ['<%=', '=%>'], tagControls: ['<%', '%>']});
// => will compile 'myfile.txt' using the var and tag controls as specified.

swig.run( tpl , locals , filepath )

Source: lib/swig.js#L715

运行一个预编译的模板函数。在浏览器中,当你已经通过Swig命令行工具预编译了你的模板时该方法非常有用。

参数

Name Type Optional Default Description
tpl function undefined Pre-compiled Swig template function. Use the Swig CLI to compile your templates.
locals object {} Template variable context.
filepath string undefined Filename used for caching the template.

返回

string: Rendered output.

例子

$ swig compile ./mytpl.html --wrap-start="var mytpl = " > mytpl.js
<script src="mytpl.js"></script>
<script>
  swig.run(mytpl, {});
  // => "rendered template..."
</script>