Drupal node templates based on node id

Code Snippet to allow you to override and specify node templates based on node id.

Put the code in your template.php file

/**
* Override or insert variables into the node templates.
*
* @param $vars
*   An array of variables to pass to the theme template.
* @param $hook
*   The name of the template being rendered ("node" in this case.)
*/

function mytheme_main_preprocess_node(&$vars, $hook) {
  switch ($hook) {
    case 'node':
      // Here is the way to switch to a different node- template based on node properties.
      if ($vars['page']) {
        // This is LIFO (Last In First Out) so put them in reverse order, i.e
        // most important last.
        $vars['template_files'] = array('node-default-page', 'node-'. $vars['node']->type .'-page', 'node-'. $vars['node']->nid .'-page');
      }
      else {
        $vars['template_files'] = array('node-'. $vars['node']->nid);
      }
    break;
  }
}
 

Leave a Reply

You must be logged in to post a comment.