spinoza spinoza - 11 months ago 328
Twig Question

twig extension render html

I want to create a twig function extension that render a twig template for a menu

/**
* Return the functions registered as twig extensions
*
* @return array
*/
public function getFunctions()
{
return array(
new \Twig_SimpleFunction('my_menu', array($this, 'myMenu')),
);
}


my function

/** render a dropdown with link to conversation
* @return string
*/
public function myMenu(\Twig_Environment $environment, $typeMenu, $menuId)
{

return $environment->render('@menuDopdown.html.twig', array(
'typeMenu' => $typeMenu,
));
}


but when i call the function i have a exeption for parametre 1

{{ my_menu(4,1280) }}



Type error: Argument 1 passed to
MenuBundle\Twig\TwigMenuExtension::myMenu() must be an instance of
Twig_Environment, integer given, called in
...\app\cache\dev\twig\07\07a15176de77b3d862b64747d9728e117749b97e55d1082eb0f0eec4ffaf12d8.php
on line 164

Answer Source

add this function, before your myMenu function, so twig will automatically pass the environment

public function getFunctions()
{
return array(
    new \Twig_SimpleFunction(
        'myMenu',
        array($this, 'myMenu'),
        array('needs_environment' => true)
    ),
);
}

or check this link for more details Render template from twig extension

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download