Using Twig for dynamic Javascript files

16,090

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.

Share:
16,090
Roderik
Author by

Roderik

Happily married, proud father, technology addict and totally into GTD and the web. I'm the Technology Director at Kunstmaan where I'm responsible for any and all things related to technology.

Updated on June 21, 2022

Comments

  • Roderik
    Roderik almost 2 years

    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 :)