2

I need to conditionally add css to a page based on the page content / URL. In the past (D6 and down) I was always advised against using hook_init() mostly because of it's weird load order in the Drupal bootstrap process. It was not uncommon to see the hook fire multiple times on a each page load - this still might be the case.

Looking at the D7 docs for hook_init() the following code example is provided:

function hook_init() {
  // Since this file should only be loaded on the front page, it cannot be
  // declared in the info file.
  if (drupal_is_front_page()) {
    drupal_add_css(drupal_get_path('module', 'foo') . '/foo.css');
  }
}

The example implies that conditional addition of css makes sense while:

To add CSS or JS that should be present on all pages, modules should not implement this hook, but declare these files in their .info file.

using a modules .info for site wide css additions.

Questions:

  • What are the options in adding css via drupal_add_css conditionally besides hook_init?

  • Has anyone had luck using the theme hook -> hook_html_head_alter():

    THEME_NAME_html_head_alter(&$head_elements) {

      if (drupal_is_front_page()) {
        drupal_add_css(drupal_get_path('module', 'foo') . '/foo.css');
      }
    

    }

  • or use the theme engine for the theme hook:

    phptemplate_html_head_alter(&$head_elements)

3

If that CSS is in your module, then the module should really be implementing the hook.

I don't think you can do anything with CSS and JS in a hook_html_head_alter(); that is really to mess with the render array before it is turned into $head by template_process_html(). Personally, I would use a template_preprocess_html(). You can add your logic there. For example,

function mymodule_preprocess_html(&$variables) {
  if (drupal_is_front_page()) {
    drupal_add_css(drupal_get_path('module', 'mymodule') . '/mymodule.css');
  }
}
| improve this answer | |
  • In terms of the module "implementing the hook", where in the module would you put drupal_add_css ? Would you use hook_init or some other function in the module? – DeeZone Feb 8 '13 at 21:32
  • 1
    I would implement it in template_preprocess_html. Updated answer. – mpdonadio Feb 8 '13 at 23:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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