Swig

A Node.js and Browser-based JavaScript Template Engine

Extending Swig

Custom Filters

Filters are simply functions that perform transformations on their first input argument.

Filters are run at render time, so they may not directly modify the compiled template structure in any way.

All of Swig's built-in filters are written in this same way. For more examples, reference the `filters.js` file in Swig's source.

To disable auto-escaping on a custom filter, simply add a property to the filter method `safe = true;` and the output from this will not be escaped, no matter what the global settings are for Swig.

Arguments

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>

Custom Tags

Swig can be extended to handle custom tags that will perform operations on full blocks of your templates. Use swig.setTag(name, parse, compile, ends, blockLevel) to add your custom tag.

All of Swig's tags are written using the same api (with a few exceptions for core modules, like extends and block). View a tag's source to see more examples to write your own custom tags.

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

Define custom parsing methods for your tag.

Arguments

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)

Compile callback for VarToken and TagToken objects.

Arguments

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

Controls whether or not a tag must have an {% end[tagName] %} declared after usage in templates.

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

Allow the tag to be written outside of {% block <name> %}{% endblock %} tags when extending a parent template.

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

Enum for 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