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

Symfony2和Twig:如何以及在何处插入PHP函数以在Twig中使用?,php,symfony,twig,twig-extension,Php,Symfony,Twig,Twig Extension,我需要在模板小枝中调用PHP函数。如何以及在何处插入该函数? 以下是我的例子: 我的控制器是: namespace BackendBundle\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use BackendBundle\Entity\Comisiones; use BackendBundle\Enti

我需要在模板小枝中调用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”。 您是否忘记了另一个命名空间的“use”语句?


缺少什么?

您需要在Twig中的类名前面加上反斜杠(例如,
\Twig\u Environment
而不是
Twig\u Environment
)。否则,PHP会将这些类名视为当前名称空间的一部分


但是,您不应该在控制器内注册自定义细枝函数、过滤器等,而应该注册自定义细枝扩展。您可以阅读更多信息。

您需要在Twig中的类名前面加上反斜杠(例如,
\Twig\u Environment
而不是
Twig\u Environment
)。否则,PHP会将这些类名视为当前名称空间的一部分


但是,您不应该在控制器内注册自定义细枝函数、过滤器等,而应该注册自定义细枝扩展。您可以阅读更多信息。

非常感谢您的快速回复!我是一个初学者与细枝和Symfony2。我不知道那篇文章告诉我。我会马上读的非常感谢你的快速回复!我是一个初学者与细枝和Symfony2。我不知道那篇文章告诉我。我马上读