Loading resources conditionally with Assetic

你说的曾经没有我的故事 提交于 2019-12-10 10:35:43

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!