1

I'm looking for a good approach to manipulate some JS code from within a module call. (Using Drupal 6.)

I have a set of JavaScript functions I need to add to a page. (Regular JavaScript, no jQuery.) Unfortunately they rely on some variables from the page they are shown on. So my current approach is to generate all the JavaScript from within PHP code which results in a whole lot of escaped strings like $output .= ' var url = "'. $url . '";' . "\n";, which is not so nice after 20-30 lines of code.

So I would like to move all the JavaScript code into it's own .js file, and find a way to inject my variables. So far, the only solution I could come up with is putting it in a temporary file, read that, modify and save it to the /files directory. But is there another, more preferred way?

1
  • @Gnuget provided "the correct" answer, I was going to post the same thing. Commented Dec 13, 2011 at 1:05

1 Answer 1

6

Drupal have a javascript array for save settings and variables, take a look here:

http://api.drupal.org/api/drupal/includes--common.inc/function/drupal_add_js/6

Check the "settings" option in that page.

A example could be:

$my_module_variables = array(
  "url"  => "http://google.com",
  "name" => "this is a variable"
);

drupal_add_js(array("my_module_vars" => $my_module_variables),'settings');

And for use it in your javascript files you can do:

console.log(drupal.settings.my_module_vars.url);
//will print http://google.com
console.log(drupal.settings.my_module_vars.name);
//will print "this is a variable"

In this way you can set javascript vars without need print javascript code, only using a php array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.