【问题标题】:Symfony Twig: Get kernel root dirSymfony Twig:获取内核根目录
【发布时间】:2017-12-05 21:04:25
【问题描述】:

我在我的 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 函数中?

编辑 1

我使用 Symfony 的自动装配,并自动装配/自动配置 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}');

【问题讨论】:

  • 发布此扩展的服务定义
  • 我使用 Symfony 的自动接线。

标签: php twig symfony-3.3


【解决方案1】:

您可以通过将扩展声明为服务,然后将服务容器传递给它来实现:

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;
}

【讨论】:

  • 如何使用php注解代替yml?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-06
  • 2020-09-29
  • 1970-01-01
  • 1970-01-01
  • 2013-05-22
  • 1970-01-01
相关资源
最近更新 更多