Twig
Twig copied to clipboard
Exception "Impossible to invoke a method ("...") on an array" when passing a function to an included template
Consider the following Twig templates:
index.html.twig
{{ obj.foo() }}
{% include "partial.twig" with {
obj2: {
foo: obj.foo
}
} %}
partial.twig
{{ obj2.foo() }}
And the following PHP script:
index.php
<?php
require_once 'vendor/autoload.php';
$loader = new \Twig\Loader\FilesystemLoader('.');
$twig = new \Twig\Environment($loader, [
'strict_variables' => true
]);
class Foo {
function foo() {
return 'foo';
}
}
echo $twig->render('index.html.twig', ['obj' => new Foo()]);
Running this script throws the exception "Impossible to invoke a method ("foo") on an array.".
It makes impossible to pass functions to included templates because Twig accepts function calls from class instances but not from its internal array representation.
We can narrow the issue to this:
echo $twig->render('index.html.twig', ['obj' => ['foo' => function() {
return 'foo';
}]]);
I'm sure this is deliberate from Twig contributors. But, what is the rational against allowing calling functions that are part of the items contained into an array?
Allowing to call methods on object is there to allow using getters (forcing to make all properties public to be able to use them would be a no-go). It can indeed be abused to do something else if you want to call another kind of method (if you don't trust the author of the templates, that's what the SandboxExtension is for)