assetic icon indicating copy to clipboard operation
assetic copied to clipboard

[feature request] add namespace support for assets

Open quazardous opened this issue 8 years ago • 2 comments

I've added namespace support to AssetFactory because I was not able to do it with my actual comprehension of assetic

class NamespaceAwareAssetFactory extends AssetFactory
{
    protected $namespaces = [];

    /**
     * Add a namespace with its path.
     * @param string $ns
     * @param string $path
     */
    public function addNamespace($ns, $path) {
        $this->namespaces[$ns] = $path;
    }

    /**
     * Will detect inputs that begin with @MyNamespace/... and replace the namespace with the corresponding path.
     *
     * @see \Assetic\Factory\AssetFactory::parseInput()
     */
    protected function parseInput($input, array $options = array())
    {
        $matches = null;
        // search for @MyNamespace/path/to/asset
        if (preg_match("|^\@([a-z_][_a-z0-9]*)/|i", $input, $matches)) {
            $ns = $matches[1];
            if (!array_key_exists($ns, $this->namespaces)) {
                throw new \RuntimeException("$ns : unknown namespace !");
            }
            $input = $this->namespaces[$ns] . substr($input, strlen($ns) + 1);
        }
        return parent::parseInput($input, $options);
    }

}

you can now have this in Twig:

{% stylesheets '@AcmeDemo/css/*.css' output="css/acme_demo" %}
                <link href="{{ asset(asset_url) }}" type="text/css" rel="stylesheet" />
{% endstylesheets %}

I'm open to comments !

quazardous avatar Jan 20 '16 18:01 quazardous

What is the use case for this ?

stof avatar Jan 20 '16 23:01 stof

Integration with Silex and a bundle lite/like feature:

https://github.com/quazardous/silex-pack

But maybe it can be achieved with a better approach. I was just wondering, Twig has namespace and it's very usefull why not Assetic. Since Symfony seams to inject namespace as well... maybe it's not a stupid request.

I must say I'm new with assetic and I'm struggling on AssetReference #790 !!

quazardous avatar Jan 20 '16 23:01 quazardous