0

I want to add some extra javascript (few files stored in my account, and some inline javascript) for a specific node. Based on the answer to this question, I tried adding a few files to the node alias "insert-pub" by doing this in the template.php in /themes/garland (just trying out the garland theme for now):

  function garland_preprocess_node(&$vars) {
     // The line below was already there.
     $vars['submitted'] = $vars['date'] . ' — ' . $vars['name'];
     // Added the lines below.
     // Want to include my javascript files and inline scripts for specific nodes.
     $node =& $vars['node'];
     debug($node);
     debug($node->type);
     if ($node->type == 'insert-pub')
     {
          drupal_add_js('/sites/all/scripts/MyLib.js', array('type' => 'file', 'scope' => 'header'));
          drupal_add_js('/sites/all/scripts/Utils.js', array('type' => 'file', 'scope' => 'header'));
          drupal_add_js('var MyAjaxLib=new MyLib();         
               function loadInput(){ alert("Hello"); }', 'inline');
     }
}

But I never see the links to the JS files or inline JS scripts in the source of the page, when I load the page in the browser by going to [www.mysite.com/insert-pub]. Where am I going wrong? Even the debug() calls above does not seem to print anything in the browser.

I am a Drupal 7 newbie, so looking forward to some hand-holding. Thanks.

4

The node type will always have an underscore as the separator (not a dash) between words so the test would be:

if ($node->type == 'insert_pub') {
  // ...
}

But it seems from your question you want to test the URL alias of the node, not the type. To do that you need to use drupal_get_path_alias() to get the node's alias, and see if it matches:

$current_node_alias = drupal_get_path_alias("node/$node->nid");
if ($current_node_alias == 'insert-pub') {
  drupal_add_js('...
} 

Make sure you've cleared Drupal's caches so the new preprocess hook can be picked up by the system. That's the only reason I can think of to explain the calls to debug() not working, as they should.

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.