0

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?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for your quick reply! I am a beginner with Twig and Symfony2 . I did not know the article that tells me. I'll read it immediately

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.