【问题标题】:Symfony2 and Twig: How and where do I insert a PHP function for use in TWIG?Symfony2 和 Twig:如何以及在何处插入 PHP 函数以在 TWIG 中使用?
【发布时间】:2016-05-13 13:22:35
【问题描述】:

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

缺少什么?

【问题讨论】:

    标签: php symfony twig twig-extension


    【解决方案1】:

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

    但是,您不应在控制器中注册自定义 Twig 函数、过滤器等,而应注册自定义 Twig 扩展。你可以阅读更多关于这个in the Symfony documentation的信息。

    【讨论】:

    • 非常感谢您的快速回复!我是 Twig 和 Symfony2 的初学者。我不知道告诉我的文章。我马上看
    猜你喜欢
    • 1970-01-01
    • 2013-07-16
    • 1970-01-01
    • 2012-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多