Main image
21st September
2008
written by david

Recently I found myself wanting to add and remove stylesheets via template.php
I thought there must be a way to do it via the _phptemplate_variables function.
Sure enough, there is:

PHP:
  1. /**
  2. * Override or insert PHPTemplate variables into the templates.
  3. */
  4.  
  5. function _phptemplate_variables($hook, $vars) {
  6.  
  7.   if($hook == 'page'){
  8.  
  9.     /* add css
  10.     * this is where css layout make themselves useful
  11.     * basically we get the current css array, add to it, and set that to var $styles
  12.     */
  13.     $new_css = drupal_add_css(); //get current css
  14.     //full page layout for node add edit and admin pages
  15.     if(arg(0) == 'admin' || arg(1) == 'add' || arg(1) == 'edit' || arg(2) == 'edit'){
  16.       // this is how you add a stylesheet
  17.       $new_css['all']['theme']['sites/all/themes/peoples_times/stylesheets/1c-b.css'] = TRUE;
  18.       $vars['hide_sidebars'] = TRUE;
  19.     }else{
  20.       //default 2 column width
  21.       $new_css['all']['theme']['sites/all/themes/peoples_times/stylesheets/2c-r.css'] = TRUE;
  22.     }
  23.     // rebuild CSS and assign it to styles var
  24.     $vars['styles'] = drupal_get_css($new_css);
  25.   }
  26. }

The example above assigns a stylesheet based on url path.
If it's a node add or edit page or admin page, it uses a 1 column layout stylesheet.
It also sets a 'hide sidebars' variable which is available in page.tpl.php


Leave a reply