Use routing to serve localized and dynamic JavaScript
Hi all,times are changing. For a lot of my projects I use a JavaScript only Web UI based on toolkits like ExtJs or qooxdoo. These applications are composed of a lot JS-Files located in the web/js folder of the Symfony-project.One of my problems i always had was that I had no chance to use Symfony Helper-Functions in those files. Especially the I18N and URL-Helper functions were missed badly.Over the time I came up with a solution the works great for me. Maybe it is usefull for you too…Add a new route
To use the symfony helpers in a javascript file you need to process them like a symfony view template. Therefore i just created a new route in the routing.yml in the config folder of the application.
dynamic_javascript:
url: /djs/:filename.js
param: { module: script, action: load }
ModuleAfter that just create the module that we specified in the routing table
$> symfony generate:module appname script
The action.class.php of this module contains the following action implementation
public function executeLoad($request) {
$this->setLayout(false);
$this->getResponse()->setContent('text/javascript');
$this->setTemplate($request->getParameter('filename'));
return ".js".chr(0);
}
As you can see there is little code needed. Just to set the content type of the response to Javascript and for using a template that is called “filename.js”.
The line return “.js”.chr(0);All you need to do is to save the JavaScript-Files in the templates folder of the script action. In your HTML/Template files you have to reference them like this
<?php use_javascript('/djs/mainapp.js'); ?>
In this JavaScript Files you can use the Helper-Functions of symfony to localize the scripts texts or to set URLs via url_for. BTW: You can use this “trick” in other files too, not only JavaScript.
Book Mark it->

Hi!,
Why just don’t use ‘use_dynamic_javascript()’ function from AssetHelper?
Best regards…
05 Apr 2009 at 12:26
[…] implementación la he tomado de este artículo llamado Use routing to serve localized and dynamic JavaScript que he encontrado googleando. Mi aporte es más que una traducción una libre interpretación con […]
26 Jun 2009 at 02:15
Using use_dynamic_javacript() - a not so well documented feature.
Here are some thoughts about it
http://goodies.lemonsoftware.eu/doku.php?id=sym:dynamicjs
29 Jan 2010 at 17:22