php 如何为 Twig 定义全局变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25812170/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to define global variable for Twig
提问by VladRia
I'm using a file serving as a form layout to overwrite certain elements (form_start, form_row, etc.). I register it like:
我正在使用一个用作表单布局的文件来覆盖某些元素(form_start、form_row等)。我注册它像:
twig:
- AcmeMainBundle:Form:formlayout.html.twig
Is there a way to use in it my variables provided along with a form?
有没有办法在其中使用我随表单提供的变量?
For example, when I send to index.html.twig
例如,当我发送到index.html.twig
array ('form' => $formView, 'var' => $var);
Var is defined only in index.html.twig.
Var 仅在index.html.twig 中定义。
So how to make vardefined in formlayout.html.twig
那么如何在formlayout.html.twig中定义var
回答by Marcin Nabia?ek
You can use addGlobal()method.
您可以使用addGlobal()方法。
For example in BaseController I use:
例如在 BaseController 中我使用:
$this->get('twig')->addGlobal('is_test', $isTest);
so in your case you should probably do:
所以在你的情况下,你可能应该这样做:
$this->get('twig')->addGlobal('var', $var);
回答by DarkMukke
In case you don't use symphony but use twig on it's own, it is as simple as:
如果您不使用 Symphony 而是单独使用 twig,则它很简单:
<?php
$loader = new \Twig_Loader_Filesystem('path/to/templates');
$twig = new \Twig_Environment($loader);
$twig->addGlobal('key1', 'var1');
$twig->addGlobal('key2', 'var2');
回答by shinraken85
To set a global variable in Twig I created a service call "@get_available_languages" (return an array) and then on my kernel.request event class I implemented the below:
为了在 Twig 中设置一个全局变量,我创建了一个服务调用“@get_available_languages”(返回一个数组),然后在我的 kernel.request 事件类上我实现了以下内容:
class LocaleListener implements EventSubscriberInterface
{
private $defaultLocale;
public function __construct($defaultLocale = 'en', ContainerInterface $container)
{
$this->defaultLocale = $defaultLocale;
$this->container = $container;
}
public function onKernelRequest(GetResponseEvent $event)
{
//Add twig global variables
$this->addTwigGlobals();
}
public function addTwigGlobals(){
//Add avaialble language to twig template as a global variable
$this->container->get('twig')->addGlobal('available_languages', $this->container->get('get_available_languages'));
}
public static function getSubscribedEvents()
{
return array(
// must be registered before the default Locale listener
KernelEvents::REQUEST => array(array('onKernelRequest', 17)),
);
}
}

