简体   繁体   English

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

[英]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 . 我需要在模板TWIG中调用PHP函数。 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: 我的Twig模板是:

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

{% endblock %}

But I get this error message: 但我收到此错误消息:

Attempted to load class "Twig_Environment" from namespace "BackendBundle\\Controller". 尝试从名称空间“ BackendBundle \\ Controller”加载类“ Twig_Environment”。 Did you forget a "use" statement for another namespace? 您是否忘记了另一个名称空间的“使用”语句?

What is missing? 什么东西少了?

You need to prefix the class names from Twig with a backslash (eg \\Twig_Environment instead of Twig_Environment ). 您需要在Twig中的类名前面加上反斜杠(例如\\Twig_Environment而不是Twig_Environment )。 Otherwise, PHP will treat those class names as if they were part of the current namespace. 否则,PHP将把这些类名视为当前名称空间的一部分。

However, you shouldn't register your custom Twig functions, filters and so on inside your controller, but register a custom Twig extension instead. 但是,您不应在控制器中注册自定义Twig函数,过滤器等,而应注册自定义Twig扩展。 You can read more about this in the Symfony documentation . 您可以在Symfony文档中阅读有关此内容的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM