Swig

A Node.js and Browser-based JavaScript Template Engine

Swig API

Object Type: SwigOpts

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.

Properties

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

Cache control for templates. Defaults to saving all templates into memory.

Examples

// 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

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.

Examples

// 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 version number as a string.

Examples

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

swig.setDefaults( options )

Source: lib/swig.js#L143

Set defaults for the base and all new Swig environments.

Parameters

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

Returns

undefined:

Examples

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

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.

Parameters

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

Returns

undefined:

swig.Swig( opts )

Source: lib/swig.js#L171

Create a new, separate Swig compile/render environment.

Parameters

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

Returns

object: New Swig environment.

Examples

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

Clears the in-memory template cache.

Returns

undefined:

Examples

swig.invalidateCache();

swig.setFilter( name , method )

Source: lib/swig.js#L270

Add a custom filter for swig variables.

Parameters

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.

Returns

undefined:

Examples

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

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.

Parameters

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.

Returns

undefined:

Examples

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

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.

Parameters

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.

Returns

undefined:

Examples

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

Pre-compile a source string into a cache-able template function.

Parameters

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

Returns

object: Renderable function and tokens object.

Examples

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

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.

Parameters

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

Returns

string: Rendered output.

Examples

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

swig.renderFile( pathName , locals , cb )

Source: lib/swig.js#L547

Compile and render a template file for final output. This is most useful for libraries like Express.js.

Parameters

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.

Returns

string: Rendered output.

Examples

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

Compile string source into a renderable template function.

Parameters

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

Returns

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

Examples

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

Compile a source file into a renderable template function.

Parameters

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.

Returns

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

Examples

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

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.

Parameters

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.

Returns

string: Rendered output.

Examples

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