Makerere University

Enter a keyword or two into the search box above and click search..

Resources Load JS & CSS Files on Specific Pages in Drupal 7

You are here

Adding CSS to a page or Node

In the template.php you will want something like:

function MYTHEME_preprocess_node($vars) {
  if (drupal_get_path_alias("node/{$vars['#node']->nid}") == 'foo') {
    drupal_add_css(drupal_get_path('theme', 'MYTHEME') . "/css/foo.css");
  }
}

An example using bartik theme to add css based on content type

function bartik_preprocess_node(&$variables) {
if(!empty($variables['node'])) {
    if($variables['node']->type == 'my_custom_content_type')
    {
      drupal_add_css(drupal_get_path('theme', 'any_theme_name') . "/css/foo.css");  
    }
  }
  // Some other code here
}

Resource : http://drupal.stackexchange.com/questions/126/any-way-to-add-css-for-a-s...

Load JS & CSS Files on Specific Pages in Drupal 7

Using a Module

function modulename_init() {
  if (request_url() == 'your-url-path') {
    drupal_add_js( /* parameters */ );
    drupal_add_css( /* parameters */ );
  }
}

Using a Template Preprocess

In your template.php:

template_preprocess_node

function yourtheme_preprocess_node(&$vars) {
  // Add JS & CSS by node type
  if( $vars['type'] == 'your-node-type') {
    drupal_add_js( /* parameters */ );
    drupal_add_css( /* parameters */ );
  }
 
  // Add JS & CSS to the front page
  if ($vars['is_front']) {
    drupal_add_js( /* parameters */ );
    drupal_add_css( /* parameters */ );
  }
 
  // Add JS & CSS by node ID
  if (drupal_get_path_alias("node/{$vars['#node']->nid}") == 'your-node-id') {
    drupal_add_js( /* parameters */ );
    drupal_add_css( /* parameters */ );
  }
}

template_preprocess_page

function yourtheme_preprocess_page(&$vars) {
  // Add JS & CSS by node type
  if (isset($vars['node']) && $vars['node']->type == 'your-node-type') {
    drupal_add_js( /* parameters */ );
    drupal_add_css( /* parameters */ );
  }
}

template_preprocess_views_view

function template_preprocess_views_view(&$vars) {
  // Get the current view info
  $view = $vars['view'];

  // Add JS/CSS based on view name
  if ($view->name == 'view_name') {
    drupal_add_js( /* parameters */ );
    drupal_add_css( /* parameters */ );
  }

  // Add JS/CSS based on current view display
  if ($view->current_display == 'current_display_name') {
    drupal_add_js( /* parameters */ );
    drupal_add_css( /* parameters */ );
  }
}

More at Source : http://www.benmarshall.me/load-js-css-specific-page-drupal-7/

Category: