Use routing to serve localized and dynamic JavaScript
13. December 2008 in Symfony
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.
|
1 |
dynamic_javascript: |
|
1 |
url: /djs/:filename.js |
|
1 |
param: { module: script, action: load } |
ModuleAfter that just create the module that we specified in the routing table
|
1 |
$> symfony generate:module appname script |
The action.class.php of this module contains the following action implementation
|
1 |
public function executeLoad($request) { |
|
1 |
$this->setLayout(false); |
|
1 |
$this->getResponse()->setContent('text/javascript'); |
|
1 |
$this->setTemplate($request->getParameter('filename')); |
|
1 |
return ".js".chr(0); |
|
1 |
} |
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
|
1 |
<?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.
g0tan said on 5. April 2009
Cristian N said on 29. January 2010
shopoto said on 20. September 2010
baiool said on 4. May 2011
Timo Haberkern said on 5. May 2011
Ray said on 24. August 2011