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.

  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) {
  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.

6 responses to Use routing to serve localized and dynamic JavaScript

  1. Hi!,
    Why just don’t use ‘use_dynamic_javascript()’ function from AssetHelper?
    Best regards…

  2. Using use_dynamic_javacript() – a not so well documented feature.

    Here are some thoughts about it :)

  3. What if we want this dynamis js not with djs/mydjs.js but a true simple js/mydjs.js

    In order that symfony try to serve the djs and if the route do not exist, apache will serve the corresponding file in the js directory if any.

    Does some one know what to add in the .htaccess to have this functionality working?

  4. Great method to put php into js files, used for more than a year, now it suddenly stopped working on my development box after upgrading to kubuntu 11.04… any ideas ?

  5. Yes. The “trick” of adding a chr(0) at the end doesn’t work on PHP 5.3.x anymore :(

  6. So is there any other solutions ?
    i tried this one but it didn’t work for me!

    thx in advance

Leave a reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>