Source: lib/swig.js#L17
Swig Options Object. This object can be passed to many of the API-level Swig methods to control various aspects of the engine. All keys are optional.
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. |
Source: lib/swig.js#L34
Cache control for templates. Defaults to saving all templates into memory.
// 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) { ... }
}
});
Source: lib/swig.js#L53
Configure Swig to use either the swig.loaders.fs or swig.loaders.memory template loader. Or, you can write your own!
For more information, please see the Template Loaders documentation.
// 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 %}'
})});
Source: lib/swig.js#L15
Swig version number as a string.
if (swig.version === "1.4.2") { ... }
Source: lib/swig.js#L143
Set defaults for the base and all new Swig environments.
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') }}
Source: lib/swig.js#L153
Set the default TimeZone offset for date formatting via the date filter. This is a global setting and will affect all Swig environments, old or new.
Name | Type | Optional | Default | Description |
---|---|---|---|---|
offset | number |
undefined |
Offset from GMT, in minutes. |
undefined:
Source: lib/swig.js#L171
Create a new, separate Swig compile/render environment.
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 =>!'
Source: lib/swig.js#L251
Clears the in-memory template cache.
undefined:
swig.invalidateCache();
Source: lib/swig.js#L270
Add a custom filter for swig variables.
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
Source: lib/swig.js#L295
Add a custom tag. To expose your own extensions to compiled template code, see swig.setExtension
.
For a more in-depth explanation of writing custom tags, see 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.
Source: lib/swig.js#L326
Add extensions for custom tags. This allows any custom tag to access a globally available methods via a special globally available object, _ext, in templates.
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);
Source: lib/swig.js#L485
Pre-compile a source string into a cache-able template function.
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.
Source: lib/swig.js#L523
Compile and render a template string for final output.
When rendering a source string, a file path should be specified in the options object in order for extends, include, and import to work properly. Do this by adding { filename: '/absolute/path/to/mytpl.html' }
to the options argument.
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!!!!
Source: lib/swig.js#L547
Compile and render a template file for final output. This is most useful for libraries like 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
Source: lib/swig.js#L592
Compile string source into a renderable template function.
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.
Source: lib/swig.js#L653
Compile a source file into a renderable template function.
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.
Source: lib/swig.js#L715
Run a pre-compiled template function. This is most useful in the browser when you've pre-compiled your templates with the Swig command-line tool.
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>