Symfony2和Twig:如何以及在哪里插入PHP函数以在Twig中使用


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

我需要在模板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,
    ));
}

我的Twig模板是:

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

但我收到了这个错误消息:

尝试从命名空间"BackendBundle''Controller"加载类"Twig_Environment"。您是否忘记了另一个命名空间的"use"语句

缺少什么?

您需要在Twig中的类名前面加一个反斜杠(例如'Twig_Environment而不是Twig_Environment)。否则,PHP将把这些类名视为当前命名空间的一部分。

然而,你不应该在控制器中注册你的自定义Twig函数、过滤器等,而是注册一个自定义Twig扩展。您可以在Symfony文档中阅读更多有关此方面的信息。