Sunday, May 30, 2010

Themes per content-type, and not only per node ID

This addresses the issue of ONLY having the possibility of theming nodes per node-ID, e.g:
"page-node-101.tpl-php"

In order to overcome this, and provide theming for each content-type (Defaults are of course "page", "story" in Drupal 6) that you may have created using CCK, you should look to modifying the code of the "theme_preprocess_page" function in your main "template.php"-file of your chosen theme.

Code to include in theme_preprocess_page
Here is the code to include...

// Add per content type pages
if (isset($vars['node'])) {
// Add template naming suggestion. It should alway use hyphens.
// If node type is "custom_news", it will pickup "page-custom-news.tpl.php".
if($vars['node']) $prefixName="page-node-";
else $prefixName="page-";
$vars['template_files'][] = $prefixName. str_replace('_', '-', $vars['node']->type);
}

And, as you will see, it gives you access to using two new template-names for your content-type:
- For views etc. node-listings: page-CONTENTTYPE.tpl.php
- For node-details views: page-node-CONTENTTYPE.tpl.php

2 comments:

  1. Content type can also be used as body class name: Define and set a global variable in theme_preprocess_page ( = $vars['node']->type)) and print the global in theme_body_class.

    ReplyDelete
  2. Of course, you are right about this approach. It is however a matter of choice and style in coding, as I see it; Do you want the bulk of your code in "template.php", or would you rather have it visible at file-level as tpl-files?

    ReplyDelete