I would like to know the names of my assets in a controller. I use assetic, so the assets names are random.
For example for my css, in my Twig I have:
{% block stylesheets %}
{% stylesheets filter='uglifycss' filter='cssrewrite'
'assets/css/bootstrap.min.css'
'assets/css/core.css'
%}
<link rel="stylesheet" href="{{ asset(asset_url) }}" />
{% endstylesheets %}
{% endblock %}
The result:
<link rel="stylesheet" href="http://local.example.com/css/c491e8f-285c78f.css" />
Now, I would like to find the name c491e8f-285c78f.css
automatically in my controller.
I tried:
var_dump($this->get('assetic.asset_manager')->getNames(),
$this->get('assetic.asset_manager')->get('c491e8f')->getTargetPath());
The result:
array(3) {
[0] => string(7) "c491e8f"
[1] => string(7) "b011b98"
[2] => string(7) "f4e7a09"
}
string(35) "_controller/css/c491e8f-285c78f.css"
It's not bad, but I have cheated to find the "c491e8f" name... How I can know it's my css asset name ? And how I can find automatically the asset path ?
As you read the source code of bundle kriswallsmith/assetic
you realize that it's not trivial to get the names of you assets
(assets have really unique names) and they are in the getNames()
array in order of appeararance in the templates.
One of the solutions is to Using Named Assets
http://symfony.com/doc/current/assetic/asset_management.html#using-named-assets
in config.yml:
assets:
bootstrap_and_core:
inputs:
- 'assets/css/bootstrap.min.css'
- 'assets/css/core.css'
you will probably also need to run the command_php app/console assetic:dump
and then:
var_dump($this->get('assetic.asset_manager')->get('bootstrap_and_core')->getTargetPath());
string 'assetic/bootstrap_and_core.css' (length=30)
Names:
var_dump($this->get('assetic.asset_manager')->getNames());
array (size=1)
0 => string 'bootstrap_and_core' (length=18)
Twig:
{% block stylesheets %}
{% stylesheets filter='uglifycss' filter='cssrewrite'
'@bootstrap_and_core'
%}
<link rel="stylesheet" href="{{ asset_url }}" />
{% endstylesheets %}
{% endblock %}
Also note:
you don't have to use {{ asset(asset_url) }}
- it would be enough to {{ asset_url }}