Using Twig for dynamic Javascript files

Roderik picture Roderik · Nov 18, 2011 · Viewed 15.9k times · Source

I'm working on a kind of dashboard mini site that has blocks with a certain functionality. Using symfony2 I have a dedicated route /instagram that gets an html fragment that shows all the images taken in our venue.

I want to refresh this block every 10 minutes, so i need to run the following javascript, in a function with a setTimeout, omitted for clarity.

jQuery('.gallery').load("/instagram", function() {
    jQuery('.gallery').cycle({
        fx: 'fade'
    });
});

This code is in "@KunstmaanDashboardBundle/Resources/public/js/instagram.js" that i run through Assetic for concatenation and optimization.

{% javascripts
    '@KunstmaanDashboardBundle/Resources/public/js/thirdparty/jquery-1.7.min.js'
    '@KunstmaanDashboardBundle/Resources/public/js/thirdparty/jquery.cycle.lite.js'
    '@KunstmaanDashboardBundle/Resources/public/js/*'
    filter='closure'
%}
    <script src="{{ asset_url }}"></script>
{% endjavascripts %}

This works, but i don't feel like this is an optimal approach because i have to hardcode the route in the load() function. To fix this i need to move the instagram.js content to the Twig template and change it to:

jQuery('.gallery').load("{{ path('KunstmaanDashboardBundle_instagram') }}", function() {
    jQuery('.gallery').cycle({
        fx: 'fade'
    });
});

But this way i lose the optimization and separation from content benefits of Assetic. And our custom code is in the most need of this optimizing.

So my question is, how can i combine Assetic Javascript (and css for that matter) with the Twig parser so i can put the code above in the instagram.js file and make it work :)

Answer

Richard Miller picture Richard Miller · Nov 18, 2011

You cannot currently process the output of Twig templates with Assetic because Assetic dumps the assets statically for production whereas the Twig templates are processed at runtime.

For this issue you may be able to use the FOSJsRoutingBundle to expose the route and process it client side, then your JavaScript could be processed with Assetic.