0

我需要在模板 TWIG 中调用 PHP 函数。我如何以及在何处插入该功能?这是我的例子:我的控制器是:

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,
    ));
}

我的树枝模板是:

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

{% endblock %}

但我收到此错误消息:

尝试从命名空间“BackendBundle\Controller”加载类“Twig_Environment”。您是否忘记了另一个名称空间的“使用”语句?

什么不见​​了?

4

1 回答 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.

于 2016-05-13T14:45:18.677 回答