Using Twig for dynamic Javascript files

2020-06-17 07:55发布

问题:

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

回答1:

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.



回答2:

I have found the solution thanks to this post How to use YUI compressor in Symfony2 routing/controller:

    $response = $this->renderView('template.html.twig');

    $path = $this->container->getParameter('kernel.root_dir');
    $ac = new \Assetic\Asset\StringAsset($response , array(new \Assetic\Filter\Yui\JsCompressorFilter($path . '/Resources/java/yuicompressor-2.4.7.jar')));

    $compressJS = $ac->dump();
    return new Response($compressJS, 200, array('Content-Type' => 'text/javascript'));