Search…
Add a Custom Twig Extension

Storybook

Step 1: Create your extension. You can create a separate package like we have done with Emulsify Twig Extensions, but you could also just put the extension directly into your project. For example, if you wanted to just add a simple Twig function that would just return the content passed in, you could create a file called simple-function.js. You can place it anywhere, but let's put it in the theme's .storybook directory. Here are the contents of our .storybook/simple-function.js file:
1
'use strict';
2
3
module.exports = simpleTwigExtension;
4
5
function simpleTwigExtension(Twig) {
6
Twig.extendFunction("simple", function(content) {
7
return content;
8
});
9
}
Copied!
You can see inside Twig.extendFunction that we are simply returning content, but you can write your extension functionality in here using JavaScript.
Step 2: Import your extension into Twig.js. In .storybook/setupTwig.js, require your extension at top:
1
const twigSimple = require('./simple-function.js');
Copied!
Below that inside of the module.exports.setupTwig function, add your new function like so:
1
module.exports.setupTwig = function setupTwig(twig) {
2
// Other stuff
3
twigSimple(twig);
4
return twig;
5
};
Copied!
Now, Storybook and Twig.js will recognize your new function, so you can use it in any twig file!
1
{{ simple('test') }}
Copied!

Drupal

There are many excellent articles around the web on how to add a new twig extension. For an example of it done within a module, see our own Emulsify Twig module.
Last modified 7mo ago
Copy link