我想注入要在twig文件中使用的全局变量.
我知道我可以将它们添加到config.yml
twig:
variable_1: variable 1
variable_2: variable 2
Run Code Online (Sandbox Code Playgroud)
但使用当前设置我无法更新config.yml.
我已经通过load()在DependencyInjection内部的扩展类中注入了yml文件,但这是我得到的,因为我不知道如何为Twig使用注入它.
您可以尝试复制此处在compilerPass中定义的TwigExtensionLoader的逻辑,例如:
public function process(ContainerBuilder $container)
{
$def = $container->getDefinition('twig');
$def->addMethodCall('addGlobal', array('my-key', 'my-value'));
}
Run Code Online (Sandbox Code Playgroud)
更详细的例子:
假设我们有一个加载的属性如下:
twig_params.yml
parameters:
foo: bar
Run Code Online (Sandbox Code Playgroud)
已经由DependencyInjection加载,我们可以添加一个编译器传递,例如:
CustomPass
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class CustomPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
$foo = $container->getParameter('foo');
$def = $container->getDefinition('twig');
$def->addMethodCall('addGlobal', array('foo', $foo));
}
}
Run Code Online (Sandbox Code Playgroud)
请参阅此处的文档,了解如何注册它.
然后你可以在树枝模板中使用通常的全局变量:
{{ foo }}
Run Code Online (Sandbox Code Playgroud)
希望这有帮助
| 归档时间: |
|
| 查看次数: |
546 次 |
| 最近记录: |