Question

I have a one-page webapp written with Symfony 2 where all css and javascript assets sit in web/static/all.js and web/static/all.js. These a linked from the intex.html.twig template in a standard way:

{% javascripts output='static/all.js' filter="?closure"
    '@MyBundle/Resources/assets/vendor/jquery/jquery.js'
    '@MyBundle/Resources/assets/...'
    '@MyBundle/Resources/assets/...'
%}
    <script type="text/javascript" src="{{ asset_url }}"></script>
{% endjavascripts %}

{% stylesheets output='staic/all.css' filter="?yui_css" combine=true
    '@MyBundle/Resources/assets/css/reset.css'
    '@MyBundle/Resources/assets/css/...'
    '@MyBundle/Resources/assets/css/...'
%}
    <link rel="stylesheet" href="{{ asset_url }}" type="text/css" media="all" />
{% endstylesheets %}

This is pretty cool already, because the browser only has to do 3 requests during the first launch and 1 or 0 requests later (all.css and all.js are cached using .htaccess).

But I want to go further and just dump all css and js into index.html similar to what google does on their homepage. This will result only one http request during the first run, which will speed up the app a little. It would be ideal to have a flag that I pass to the template or keep in twig globals that will enable switching between two modes on demand.

{%if dumpAssetsIntoTemplate %}
    {# all js and css here #}
{% else %}
    {# asset urls #}
{% endif %}

How could this be done with minimum pain?

Was it helpful?

Solution

If you look at Twig reference about Twig extensions you can see that the render function takes a path or a URL.

{{ render(path('route', {params})) }}
{{ render(url('route', {params})) }}

Quoting the usage from the doc "This will render the fragment for the given controller or URL".

So I would try that:

<style type="text/css">
{% stylesheets output='static/all.css' filter="?yui_css" combine=true
    '@MyBundle/Resources/assets/css/reset.css'
    '@MyBundle/Resources/assets/css/...'
    '@MyBundle/Resources/assets/css/...'
%}
    {{ render(asset_url) }}"
{% endstylesheets %}
</style>

Same approach with your Javascript files.

If it doesn't work, you'll probably want to tweak the settings of the Assetic bundle in particular the setting named use_controller.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top