Friday 13 July 2012

CREATE A PAGE TEMPLATE FOR ANYTHING YOU WANT


Out of the box, Drupal provides the ability to create page templates for different pages/sections. However, its flexibility is relatively limited, in our opinion. This page on drupal.org shows the following page.tpl.php naming conventions and uses:
1. page.tpl.php (global)
2. page-front.tpl.php (front page)
3. page-node-edit.tpl.php (node edit)
4. page-node-[#].tpl.php (specific node)
5. page-node.tpl.php (nodes - global)
6. page-[internal/path].tpl.php (specific path)
This is an interesting list. While it does accommodate for quite a bit, it misses a few seemingly obvious use-cases. Now, this of course depends on your site and its needs. It may suit your purposes just fine. On the off chance it doesn't, however, take a little trip with us down the rabbit hole and find out how to create your own page templates for literally ANYTHING you want.

Page template per content type

One of the things that's missing from the list above is "page-content-type.tpl.php" (e.g. page-blog.tpl.php). What if you want your Blog nodes to use a different structure than your Page nodes?
In your theme's template.php file (create it if it doesn't exist), add the following:
<?php
...
function YOURTHEME_preprocess(&$vars, $hook) {
global $user;
switch($hook) {
case 'page':
// Check to see if the page is a node
if ($node = node_load(arg(1)) && arg(0) == 'node') {
$node = node_load(arg(1));
$types = node_get_types('names');
// Check to see if there is a valid Content Type
if (in_array($node->type, $types)) {
$suggestions[] = "page-node-$node->type";
$vars['template_files'] = array_merge($variables['template_files'], $suggestions);
}
}
}
}
...
?>

Page template for any section

Or, what if you want to add a page-template for an entire section, based on the path (e.g. foo/bar/*)?
<?php
...
function YOURTHEME_preprocess(&$vars, $hook) {
global $user;
switch($hook){
case 'page':
// Check path for /foo/bar/*
if(arg(0) == 'foo' && arg(1) == 'bar' && arg(3)) {
$suggestions[] = "page-foo-bar-section.tpl.php";
}
}
}
...
?>
Just don't forget to rebuild the theme registry if the template.php file is new, or your site won't pick the changes up!
using phptemplate_preprocess_page function
function phptemplate_preprocess_page(&$vars) {
$vars['tabs2'] = menu_secondary_local_tasks();
if(isset($vars['node']) && !empty($vars['node']) && arg(0)=='node' && is_numeric(arg(1))){
$node= $vars['node'];
$vars['template_files'][] = "page-node-".$node->type;
}
// Hook into color.module
if (module_exists('color')) {
_color_page_alter($vars);
}
}
Now put the  page-node-[node-type].tpl.php in your Active theme directory.

No comments:

Post a Comment