muriqui
Great designs deserve great code.

Adding variables to Drupal.settings

This discussion is closed: you can't post new comments.

If you’ve ever looked at the HTML code that your Drupal site spits out, you may have noticed something like this in the <head> section:

jQuery.extend(Drupal.settings, { "basePath": "/" });

And you may have thought, “So what? Drupal stores the base path in an array. Big whoop.” Well, what’s cool about this is that it’s one of the ways Drupal makes it easy for you to pass values computed in PHP to your jQuery scripts.

So how do we plug our own values into Drupal.settings? The answer is a function you’re probably already familiar with: drupal_add_js. Mostly, it’s used in themes and modules to import script files or inline code, but a quick look at its API definition shows that it also has a ‘setting’ mode. That’s our access point for Drupal.settings.

Here’s an example from my own site. The slider plug-in that I use in my portfolio needs to reference a couple of image files in my theme. Rather than hardcoding the theme path in script.js (which wouldn’t be very portable), I just add this line to my template.php:

<?php
drupal_add_js
(array('muriqui' => array('theme' => path_to_theme())), 'setting');
?>

The first argument is an associative array, and the second argument tells drupal_add_js to add these values to the Drupal.settings array. Notice that I’m adding my new ‘theme’ value in a nested array under the parent value ‘muriqui,’ which is the name of my theme. This is a best practice to avoid a conflict with values defined by other modules. Now, my output in <head> looks like this:

jQuery.extend(Drupal.settings, { "basePath": "/", "muriqui": { "theme": "sites/default/themes/muriqui" } });

To reference this value in my scripts, I just use Drupal.settings.muriqui['theme']. That’s a fairly simple example, but it opens the door to all sorts of nifty dynamic stuff (context-aware UI, anyone?). And it’s a lot cleaner than a bunch of inline script code to define variables.

Do you have any neat tricks for using Drupal.settings? Tell us about them in the comments.

Category:

Comments

How to theme user login form in a drupal site? Let’s say, we need to alter the descriptions in user login form.