How to safely add a stylesheet in phptemplate_preprocess_page()

When you write a custom module, a lot of times you also need to add a stylesheet. The safest place to do this, is in your implementation of hook_init(). But sometimes, you have to wait until your phptemplate_preprocess_page() kicks in before deciding what stylesheets to add. In that case, there a few things you should take into account, otherwise you might overwrite the stylesheet changes done by other modules.

Let's have a look at the different variables and functions needed to add a custom stylesheet in your preprocess_page:

  • $variables['css']: an array containing all your stylesheet files defined in themes or modules.
  • $variables['styles']: a string with the rendered version of your css, as it will be printed in your page.tpl.php.
  • drupal_get_css(): returns variables['styles'].
  • drupal_get_css($css): returns a themed version of the $css array that is supplied as an argument.
  • drupal_add_css($path, $type): adds a stylesheet to $variables['css'];
  • drupal_add_css(): returns $variables['css'], but without any changes done in other hook_preprocess_page() calls.

How to get the current css

In some cases, it is necessary to get the current list of stylesheets, so that you can make some changes to it. If you simply plan on adding a stylesheet, you can skip this step.

Quite often modules use this to get an array with all stylesheets:

1
$css = drupal_add_css();

However, this function does not return any changes that other phptemplate_preprocess_page() functions might have made, so don't use it.

Instead, use $variables as a starting point:

1
$css = $variables['css'];

Add your custom stylesheet(s)

This is a simple step: just use drupal_add_css($path, $type) to add your own stylesheet, e.g.:

1
drupal_add_css(drupal_get_path('module', 'mymodule') .'/mymodule.css', 'module');

What to return

To be sure that our changes don't get overwritten by other modules, we have to make sure that the array of stylesheets($variables['css']) as well as the rendered string ($variables['styles']) are updated. Here is a full example on how to safely add your stylesheet:

1
2
3
4
5
6
// Add the css.
drupal_add_css(drupal_get_path('module', 'mymodule') .'/mymodule.css', 'module');
// Update $variables['css'].
$variables['css']['all']['module'][drupal_get_path('module', 'mymodule').'/mymodule.css'] = TRUE;
// Update $variables['styles'].
$variables['styles'] = drupal_get_css();

The key is to update $variables['css'] so that other modules can use it as a starting point. That's it!

Comments

Re: How to safely add a stylesheet in ...

In D7 you can attach stuff like that in forms to #attached.

$form['#attached']['css'][] = 'some/css/here.css';

And that's when you usually (?) want it.

Rudie
20/10/2011
The content of this field is kept private and will not be shown publicly.
By submitting this form, you accept the Mollom privacy policy.