Swig

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

模板加载器

内置加载器

swig.loaders.fs(basepath, encoding)

Source: lib/loaders/filesystem.js

从文件系统中加载模板。

参数

Name Type Optional Default Description
basepath string ''

Path to the templates as string. Assigning this value allows you to use semi-absolute paths to templates instead of relative paths.

encoding string 'utf8'

Template encoding

swig.setDefaults({ loader: swig.loaders.fs() });
// Load Templates from a specific directory (does not require using relative paths in your templates)
swig.setDefaults({ loader: swig.loaders.fs(__dirname + '/templates' )});

swig.loaders.memory(mapping, basepath)

Source: lib/loaders/memory.js

从一个已经给出的对象映射中加载模板。

参数

Name Type Optional Default Description
mapping object

Hash object with template paths as keys and template sources as values.

basepath string

Path to the templates as string. Assigning this value allows you to use semi-absolute paths to templates instead of relative paths.

var templates = {
  "layout": "{% block content %}{% endblock %}",
  "home.html": "{% extends 'layout.html' %}{% block content %}...{% endblock %}"
};
swig.setDefaults({ loader: swig.loaders.memory(templates) });

定制加载器

Swig允许你自己编写模板加载器,这样你的模板就可以来自你喜欢的存储媒介,而不必成为核心库的一部分。

模板加载器由两个方法组成:resolveload。每个方法由Swig在内部使用,在Swig尝试解析和编译之前加载模板的源文件。

resolve(to, from)

Resolves to to an absolute path or unique identifier. This is used for building correct, normalized, and absolute paths to a given template.

参数

Name Type Description
to string

Non-absolute identifier or pathname to a file.

from string

If given, should attempt to find the to path in relation to this given, known path.

load(identifier, cb)

加载一个模板。Given a unique identifier found by the resolve method this should return the given template.

参数

Name Type Description
identifier string

Unique identifier of a template (possibly an absolute path).

cb function

Asynchronous callback function. If not provided, this method should run synchronously.

例子

// A theoretical memcached loader
var path = require('path'),
  Memcached = require('memcached');
function memcachedLoader(locations, options) {
  var memcached = new Memcached(locations, options);
  return {
    resolve: function (to, from) {
      return path.resolve(from, to);
    },
    load: function (identifier, cb) {
      memcached.get(identifier, function (err, data) {
        // if (!data) { load from filesystem; }
        cb(err, data);
      });
    }
  };
};
// Tell swig about the loader:
swig.setDefaults({ loader: memcachedLoader(['192.168.0.2']) });