简体   繁体   中英

Symfony Twig: Get kernel root dir

I have setup the following configuration over my Symfony project:

twig:
    debug: '%kernel.debug%'
    strict_variables: '%kernel.debug%'
    globals:
      web_dir: "%kernel.root_dir%/../web"

And I have done the following twig symnfony function (as seen in 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;
    }

}

My problem is on how I will get the value of the web_dir global into the versionedAsset function?

Edit 1

I use the Symfony's autowire and I autowire/autoconfigure the AllExtentions class:

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

You can achieve this by declaring your extension as a service and then passing a service container to it:

twig.all.extensions:
    class: AppBundle\Twig\AllExtentions
    arguments:
        - @service_container
    tags:
        - { name: twig.extension }

After this add a __construct() method to your Extension and use it to get a your web_dir variable:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM