-
Notifications
You must be signed in to change notification settings - Fork 275
Extending twig.js
Dorian Marchal edited this page Jan 22, 2020
·
4 revisions
There are several aspects of twig.js that can be extended with custom functionality.
They are:
- Functions
- Filters
- Tests
- Tags
Custom functions can be added through Twig.extendFunction(name, definition)
For example, a function that repeats a value could look like:
Twig.extendFunction("repeat", function(value, times) {
return new Array(times+1).join(value);
});
And you can use it in a template like:
{{ repeat("_.", 10) }}
{# output: _._._._._._._._._._. #}
Custom filters can be added through Twig.extendFilter(name, definition)
For example, if you wanted to add a filter that reversed words in a sentence, you could do the following:
Twig.extendFilter("backwords", function(value) {
return value.split(" ").reverse().join(" ");
});
Then, in your templates you can use:
{{ "a quick brown fox"|backwords }}
outputs: fox brown quick a
Custom filters with arguments are also supported:
Twig.extendFilter('catify', (value, args) =>
args.reduce(
(newString, toCatify) => newString.replace(toCatify, 'cat'),
value
)
);
{{ "the quick brown fox jumps over the lazy dog"|catify('fox', 'dog') }}
outputs: the quick brown cat jumps over the lazy cat