问题
Is it possible to load assets conditionally with Assetic?
For example (peusocode):
load resource1.js
load resource2.js
if condition = true
load resource3.js
endif
output combined.js
回答1:
No it's not possible because assetic files are compiled on the server side, so assetic don't have access to the value of your variable at runtime.
A solution could be to add a second assetic tag
// the first assetic tag
{% if condition %}
// an other assetic tag
{% endif %}
回答2:
I came across to exactly the same problem. As julesbou already mentioned, it is necessary to add several assetic tags.
My particular case scenario was to render a different background depending on the environment : light grey for the DEV environment, and white for the PROD environment.
I used two CSS files: basic.css and debug.css
This is my solution (Symfony 2) (within the tags in an twig template for HTML5:
{# Common CSS stylesheets--------------------------------#}
{% stylesheets
'@XStitchPublicBundle/Resources/public/css/basic.css'
%}
<link rel="stylesheet" href="{{ asset_url }}" />
{% endstylesheets %}
{# ----------------------------------------------------- #}
{#
Conditional CSS stylesheet. Depend on the environment
#}
{% set environment = app.environment %}
{% if environment == 'dev' %}
{# Condition: Dev environment#}
{% stylesheets
'@XStitchPublicBundle/Resources/public/css/debug.css'
%}
<link rel="stylesheet" href="{{ asset_url }}" />
{% endstylesheets %}
{% endif %}
来源:https://stackoverflow.com/questions/8417521/loading-resources-conditionally-with-assetic