User Tools

Site Tools


php:dynamicjs

How to use use_dynamic_javascript() helper in symfony

29.01.2010

Or in other words, how to include php into javascript files in symfony. This is one of the things I banged my head against the wall for days, and then discovered that symfony made it as simple as possible :)

Q: First, what use_dynamic_javascript() does? A: It adds a dynamic javascript to the response object.
Q: Why we need this? A: Read on…

Assume we have a javascript file with the following code in it (or similar, all that matters are php functions - here url_for helper):

var a = <?php echo url_for('@homepage');?>;
alert(a);

1. Include the route for this javascript in the template of choice

in your template file, for example templates/somethingSuccess.php

<?php use_dynamic_javascript("@testjavascript"); ?>
... more code...

2. Create the route

in routing.yml file, create the new route for it (example module is yourmodule and action testjs):

testjavascript:
    url: /yourmodule/testjs
    param: { module: yourmodule, action: testjs }

3. Create the action

in actions.class.php for that module ( actions/actions.class.php ), create an empty function for the route previously created:

class yourmoduleActions extends sfActions {
    ... more code...
    public function executeTestjs() {}

4. Create in fact the javascript file

This is a javascript file, but with php extension. It should be in templates/ directory and it should have the following name: testjsSuccess.js.php (it should match the action executeTestjs(), ok?)

var a = <?php echo url_for('@homepage');?>;
alert(a);

Do a php symfony cc to avoid some headaches, and then refresh/call the action what will activate the template (somethingSuccess.php) which includes the javascript call. The call will look like

http://.../yourmodule/testjs?sf_format=js

5. And there's even more! Quicker and simpler way to do it!

Asumming that you have the same templates/somethingSuccess.php, modify the call for javascript from:

<?php use_dynamic_javascript("@testjavascript"); ?>
to
<?php use_dynamic_javascript("@testtemplate"); ?>

and in routing.yml

testtemplate:
    url: /yourmodule/something.:sf_format
    param: { module: yourmodule, action: something, sf_format: html }
    requirements:
        sf_format: (?:html|js)

which is exactly the route which is applied to our template (you should already have it; in fact all you have to do is to modify the actual route for “something” action, to accept also sf_format:js.

Then, put all your javascript code into a file called exactly as the template, but with .js addition (example: templates/somethingSuccess.js.php)

If you have suggestions, comments or similiar, send me a message on the email address indicated on the bottom of the page (sorry, no blog here :P)

php/dynamicjs.txt · Last modified: 2013/03/16 17:40 (external edit)