【发布时间】:2018-11-06 08:33:30
【问题描述】:
我按照Symfony 3.4 docs 上的示例在运行时加载 Twig 扩展,但它没有加载:我做错了什么?
输入:src/PlotlyBundle/Twig/AppRuntime.php
<?php
namespace PlotlyBundle\Twig;
class AppRuntime
{
public function __construct()
{
}
public function biDraw()
{
return 'awesome text here';
}
}
输入:src/PlotlyBundle/Resources/config/services.yml
services:
plotly.twig_runtime:
class: PlotlyBundle\Twig\AppRuntime
public: true
tags:
- { name: twig.runtime }
输入:src/PlotlyBundle/Twig/AppExtension.php
<?php
namespace PlotlyBundle\Twig;
use PlotlyBundle\Twig\AppRuntime;
class AppExtension extends \Twig_Extension
{
public function getFunctions()
{
return [
new \Twig_SimpleFunction(
'bi_draw',
array(AppRuntime::class, 'biDraw')
),
];
}
}
输入:src/AppBundle/Controller/DashboardController.php
$twig = $this->get('plotly.twig_runtime');
return $this->render(
'dashboard/index.html.twig'
);
输入:app/Resources/views/dashboard/index.html.twig
{{ bi_draw() }}
【问题讨论】:
-
感觉不对。文档是不是错了?你可以试试
class: PlotlyBundle\Twig\AppExtension吗? -
^ 不,没有错——你是自动接线的吗?否则你需要用
twig.extension标记它 -
我已经尝试过:使用 xdebug 时,我看到构造函数被调用但 getFunctions 未被调用。我应该向我的包(PlotlyBundle)添加依赖注入吗?
-
我在service.yml中添加了标签
-
你能用它更新你的帖子吗?您的服务容器的自动配置选项是否已启用? (symfony.com/doc/3.4/…)