How to use a YUI compressor in a Symfony2 router / controller

How to use YUI compressor with the following scenario:

routing.yml

js_route: pattern: /foo/bar.{_format} defaults: { _controller: FooBundle:Default:JS } requirements: _format: js 

Defaultcontroller.php

 public function JSAction() { // ... // content for JS file is being generated // ... return $this->render('FooBundle:Default:bar.js.twig', $returnarray); // ... } 

I know how to use it in my branch templates (for example, {% javascripts '@ FooBundle / Resources / public / js / *' filter = '? Yui_js'%}), but, unfortunately, not higher.

Any clues? Thanks!

+1
source share
1 answer

I really do not suggest you do this because the YUI JS compressor will be loaded every time a resource is requested. But this is one way to do it anyway.

Note that to simplify a simple example, I excluded the extra code to correctly determine your web root and the location of the jar file.

 $path = $this->container->getParameter('kernel.root_dir'); $ac = new \Assetic\Asset\AssetCollection(array( new \Assetic\Asset\FileAsset($path . '/../src/WebBundle/Resources/public/js/jquery.longclick.js') ), 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')); 

Also note: you are not limited to FileAsset () only. There are other classes such as StringAsset (), etc., so you can dynamically create content.

0
source

All Articles