11 August 2011

Drupal: How to add css file to specific drupal page.

We all know in Drupal, we can add css files in theme folder via info file, through the declaration [stylsheets][all][] = style.css.

We can go on add as many css files. All CSS files added through info file will be available through out the site.

If we are working to develop a small website, this will be a right solution, where we won't worry about the performance / maintainability etc.

But when we work for large scale web portals, we would plan for each minor aspects of the web portal. In this case we would have many pages, so we would have a large / heavy CSS file.

Now, we want to split the CSS file in theme folder and we want to add them only on required pages.

So if we have our module, Hook_init is the right place to add the css, we can add the css file, by calling drupal_add_css function.

Hook_init will be called on every page callback, but it will not called when the page is cached. Don't worry cached page already will have your css.

In module also, if we have page callback, then we can call the drupal_add_css inside the callback function, which makes sure, only when the callback function is called the css will add to the page.

Don't try to use the drupal_add_css in page tpl's which won't work, because already variables are generated in preprocess function.

Here i will explain you to add css file in hook_init for multiple pages.

The code will look like

  // declare an array to list the pages we need to add css, 
//This will be easy to add pages in future. $pages = array ( 'node/add/page', 'node/%/edit', 'home', 'home/*', ); // convert the array to string, append a newline to every array element. $pages = implode(chr(10),$pages); // this drupal_get_path_alias
// will return the alias path if found or the original one which is passed. $path = drupal_get_path_alias($_GET['q']); // Compare with the internal and path alias (if any). $page_match = drupal_match_path($path, $block->pages); if ($path != $_GET['q']) { $page_match = $page_match || drupal_match_path($_GET['q'], $block->pages); } if ($page_match) { drupal_add_css(drupal_get_path('xyz','module'),'module'); } ?>

Place this snippet inside the hook_init, now your css will be added only on above listed pages in $pages array.