我在Symfony项目中设置了以下配置:
twig:
debug: '%kernel.debug%'
strict_variables: '%kernel.debug%'
globals:
web_dir: "%kernel.root_dir%/../web"
我已经完成了以下twig symnfony函数(如Symfony generate cdn friendly asset url中所示):
namespace AppBundle\Twig;
class AllExtentions extends \Twig_Extension
{
public function getFunctions()
{
return array(
new \Twig_SimpleFunction('versionedAsset',array($this,'versionedAsset'))
);
}
/**
* Gebnerate a cdn friendly url for the assets.
* @param string $path The url of the path RELATIVE to the css.
* @return string
*/
public function versionedWebAsset($path)
{
// Set the value of the web_dir global
// $webDir=
$hash=hash_file("sha512",$path);
return $path."?v=".$hash;
}
}
我的问题在于我如何将web_dir
全局的值转换为versionedAsset函数?
我使用Symfony的autowire并自动装配/自动配置AllExtentions
类:
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
// To use as default template
$definition = new Definition();
$definition
->setAutowired(true)
->setAutoconfigured(true)
->setPublic(false);
$this->registerClasses($definition, 'AppBundle\\', '../../src/AppBundle/*', '../../src/AppBundle/{Entity,Repository,Resources,Tests}');
答案 0 :(得分:2)
您可以通过将您的扩展程序声明为服务,然后将服务容器传递给它来实现此目的:
twig.all.extensions:
class: AppBundle\Twig\AllExtentions
arguments:
- @service_container
tags:
- { name: twig.extension }
之后,在您的扩展程序中添加__construct()
方法并使用它来获取web_dir
变量:
/**
* ContainerInterface $container
*/
public function __construct($container)
{
$this->container = $container;
}
/**
* Gebnerate a cdn friendly url for the assets.
* @param string $path The url of the path RELATIVE to the css.
* @return string
*/
public function versionedWebAsset($path)
{
$webDir=$this->container->get('twig')->getGlobals()['web_dir'];
$hash=hash_file("sha512",$path);
return $path."?v=".$hash;
}