Search code examples
symfonyassetssymfony-2.7

Symfony 2.7+ Asset Custom Version Strategy config


I have successfully set up my Symfony 2.7.x installation to use standard Asset Version Strategies (EmptyVersionStrategy and StaticVersionStrategy) but would like to implement a Custom Version Strategy like a date-based strategy or similar.

currently, I have

config.yml

framework:
    assets:
        version: 'v1' # or ~ for EmptyVersionStrategy

Since the version value seems to implement the strategy and also the value, how do I configure a custom strategy?

I have already read the Asset Blog article and the less-than-complete docs.


Solution

  • You can replace EmptyVersionStrategy by ease, just override the service as you can see below:

    app/config/services.yml

    services:
        assets.empty_version_strategy:
            class:      FooBundle\Twig\Extension\AssetVersionStrategy
            arguments:  ["%kernel.root_dir%"]
    

    src/FooBundle\Twig\AssetVersionStrategy.php

    namespace FooBundle\Twig\Extension;
    
    use Symfony\Component\Asset\VersionStrategy\VersionStrategyInterface;
    
    
    /**
     * AssetVersionStrategy (Twig)
     *
     * @author Your Name <you@example.org>
     * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
     */
    class AssetVersionStrategy implements VersionStrategyInterface
    {
        /**
         * @var string
         */
        private $root;
    
        /**
         * @param string $root
         */
        public function __construct($root)
        {
            $this->root = $root;
        }
    
        /**
         * Should return the version by the given path (starts from public root)
         *
         * @param string $path
         * @return string
         */
        public function getVersion($path)
        {
            return $path;
        }
    
        /**
         * Determines how to apply version into the given path
         *
         * @param string $path
         * @return string
         */
        public function applyVersion($path)
        {
            return sprintf('%s?v=%s', $path, $this->getVersion($path));
        }
    }