Search code examples
phpsymfonytwigtwig-extension

Symfony2 and Twig: How and where do I insert a PHP function for use in TWIG?


I need to call a PHP function within a template TWIG . How and Where I insert that function? Here my example: My Controller is:

namespace BackendBundle\Controller;

use Symfony\Component\HttpFoundation\Request;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use BackendBundle\Entity\Comisiones;
use BackendBundle\Entity\Liquidaciones;
use BackendBundle\Form\ComisionesType;
use BackendBundle\Form\LiquidacionesType;

    /**

* Comisiones controller.
 *
 */
class ComisionesController extends Controller
{
    /**
     * Lists all Comisiones entities.
     *
     */
    public function indexAction()
    {
       $twig = new Twig_Environment($loader);
        $function = new Twig_SimpleFunction("decir_hola", function () {
         $saludo='Hola!';
         return $saludo;
        }); 
        $em = $this->getDoctrine()->getManager();

    $comisiones = $em->getRepository('BackendBundle:Comisiones')->findComisio();

    return $this->render('comisiones/index.html.twig', array(
        'comisiones' => $comisiones,
    ));
}

My Twig template is:

{% block body %}
{{decir_hola()}}

{% endblock %}

But I get this error message:

Attempted to load class "Twig_Environment" from namespace "BackendBundle\Controller". Did you forget a "use" statement for another namespace?

What is missing?


Solution

  • You need to prefix the class names from Twig with a backslash (e.g. \Twig_Environment instead of Twig_Environment). Otherwise, PHP will treat those class names as if they were part of the current namespace.

    However, you shouldn't register your custom Twig functions, filters and so on inside your controller, but register a custom Twig extension instead. You can read more about this in the Symfony documentation.