hous hous - 3 months ago 15
Twig Question

Twig extension: render template with variables

I have created a twig extension te render a view with some variables , but I have this error

An exception has been thrown during the rendering of a template ("Notice: Array to string conversion")
in :Backend\twig:activate.html.twig at line 1.


This is the Class extension:

namespace AppBundle\Twig;

class ActivateExtension extends \Twig_Extension
{
public function getFilters()
{
return array(
new \Twig_SimpleFilter('activate', array($this, 'booleanFilter'), array('is_safe' => array('html'),
'needs_environment' => true)),
);
}

public function booleanFilter(\Twig_Environment $twig, $var1, $var2)
{

return $twig->render(':Backend/twig:activate.html.twig', array(
'var1' => $var1,
'var2' => $var2
));
}

public function getName()
{
return 'activate_extension';
}
}


this is the view to be rendred:

//test
{{ var1 }}<br>
{{ var2 }}


and this is how the filter is called in the other view:

{{ entity.activate|activate('test var1', 'test var2') }}

Answer

Referring to the TWIG developer guide about Filters:

When called by Twig, the PHP callable receives the left side of the filter (before the pipe |) as the first argument and the extra arguments passed to the filter (within parentheses ()) as extra arguments.

So the first argument of the php function is the value of entity.activate probably the array of the errors, then the other params are passed as arguments. As example you should change your filters as follow:

public function booleanFilter(\Twig_Environment $twig, $activate, $var1, $var2)
{

    return $twig->render(':Backend/twig:activate.html.twig', array(
        'var1' => $var1,
        'var2' => $var2
    ));
}

Hope this help. Sorry for my comment about twig functions