Recipes

Reusing a stateful Node Visitor

When attaching a visitor to a TwingEnvironment instance, the parser uses it to visit all templates it compiles. If you need to keep some state information around, you probably want to reset it when visiting a new template.

This can be easily achieved with the following code::

let someTemplateState = {};

const enterNode = (node) => {
    if (node.is("module")) {
        // reset the state as we are entering a new template
        someTemplateState = {};
    }

    // ...

    return node;
};