twig.js icon indicating copy to clipboard operation
twig.js copied to clipboard

Functions passed as additional variable of the include statement are executed

Open ericmorand opened this issue 7 years ago • 2 comments

Consider the following test:

        twig({
            id:   'include-with-function',
            path: 'test/templates/include-with-function.twig',
            async: false
        });

        // Load the template
        twig({ref: 'include-with-function'}).render({
            test: function(d) {
                return 'ABC' + d;
            }
        }).should.equal( "ABCD" );

with test/templates/include-with-function.twig consisting of

{% include "inc-function.twig" with {
    test: test
} %}

and test/templates/inc-function.twig consisting of

{{ test('D') }}

This test will fail with the error:

Error parsing twig template test/templates/inc-function.twig: TwigException: test function does not exist and is not defined in the context

Now consider the same test with test/templates/include-with-function.twig consisting of

{% include "inc-function.twig" %}

This test will pass.

The only difference between those two test in that in the first one, test is passed as an additional variable to the include statement.

The thing is function passed as additional variable of the include statement are executed:

{% include "inc-function.twig" with {
    test: test <---------------- test is executed and the result of its execution is stored into `test` property
} %}

Thus, in the included template, test is not a function but a string containing 'ABCundefined'.

Is this an expected behavior?

ericmorand avatar Mar 21 '17 23:03 ericmorand

with is causing lots of problems all over the place.

If it doesn't behave like twig-PHP, then it isn't expected behaviour.

dave-irvine avatar Mar 22 '17 08:03 dave-irvine

OK, I'll see what I can do.

ericmorand avatar Mar 22 '17 08:03 ericmorand