[英]symfony twig extension get config variable
I'm trying to get config variable from custom twig extension. 我正在尝试从自定义树枝扩展名获取配置变量。
how can I get someVar from config ? 如何从config中获取someVar?
// src/AppBundle/Twig/AppExtension.php
namespace AppBundle\Twig;
class AppExtension extends \Twig_Extension
{
public function getFilters()
{
return array(
new \Twig_SimpleFilter('price', array($this, 'priceFilter')),
);
}
public function priceFilter($number, $decimals = 0, $decPoint = '.', $thousandsSep = ',')
{
$price = number_format($number, $decimals, $decPoint, $thousandsSep);
// HOW TO ACCESS TO CONFIG VARIABLE
$price = '$'.$price;
return $price;
}
public function getName()
{
return 'app_extension';
}
}
# app/config/services.yml
services:
app.twig_extension:
class: AppBundle\Twig\AppExtension
public: false
tags:
- { name: twig.extension }
twig:
debug: "%kernel.debug%"
strict_variables: "%kernel.debug%"
globals:
someVar: "someValue"
{{someVar}} is right if you need to read it inside a template {{someVar}}是正确的,如果您需要在模板中阅读
but if you need to get globals INSIDE the extension right there where you placed // HOW TO ACCESS TO CONFIG VARIABLE, then use follow code: 但是,如果您需要在扩展名中直接放置全局变量,//在此位置,//如何访问以配置变量,然后使用以下代码:
/* @var $globals \Twig_Environment */
$globals = $this->container->get('twig');
$vars = $globals->getGlobals();
var_dump($vars['someVar']);
Update: you will need to pass the container inside the extension, so add constructor 更新:您将需要在扩展内传递容器,因此添加构造函数
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
and pass container at service.yml 并在service.yml传递容器
twig.extension.name:
class: App\SomeBundle\Extensions\ClassTwig
arguments: [@service_container]
tags:
- { name: 'twig.extension' }
You would access it as a normal variable. 您可以将其作为普通变量访问。
{{someVar}}
See here: 看这里:
http://symfony.com/doc/current/cookbook/templating/global_variables.html http://symfony.com/doc/current/cookbook/templating/global_variables.html
I hope that helps! 希望对您有所帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.