symfony twig 扩展获取配置变量
symfony twig extension get config variable
我正在尝试从自定义 twig 扩展中获取配置变量。
如何从配置中获取 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}}
看这里:
http://symfony.com/doc/current/cookbook/templating/global_variables.html
希望对您有所帮助!
{{someVar}} 是正确的,如果你需要在模板中阅读它
但是如果你需要在你放置//如何访问配置变量的地方获取扩展内部的全局变量,那么使用下面的代码:
/* @var $globals \Twig_Environment */
$globals = $this->container->get('twig');
$vars = $globals->getGlobals();
var_dump($vars['someVar']);
更新:
您将需要在扩展中传递容器,因此添加构造函数
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
并在 service.yml
传递容器
twig.extension.name:
class: App\SomeBundle\Extensions\ClassTwig
arguments: [@service_container]
tags:
- { name: 'twig.extension' }
我正在尝试从自定义 twig 扩展中获取配置变量。
如何从配置中获取 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}}
看这里:
http://symfony.com/doc/current/cookbook/templating/global_variables.html
希望对您有所帮助!
{{someVar}} 是正确的,如果你需要在模板中阅读它
但是如果你需要在你放置//如何访问配置变量的地方获取扩展内部的全局变量,那么使用下面的代码:
/* @var $globals \Twig_Environment */
$globals = $this->container->get('twig');
$vars = $globals->getGlobals();
var_dump($vars['someVar']);
更新: 您将需要在扩展中传递容器,因此添加构造函数
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
并在 service.yml
传递容器 twig.extension.name:
class: App\SomeBundle\Extensions\ClassTwig
arguments: [@service_container]
tags:
- { name: 'twig.extension' }