If you're like me, you probably use complicated node types with many fields and custom layouts. If that's the case, the default printer-friendly rendering of nodes may not suit you. In this code snippet I'll explain how you can override the templates and how I got to this step.
The first step when making modifications like this is to determine how the html was generated (template, function, callback, etc). Take a look at the query string for a printer friendly page: book/export/html/YOURNODEID. If you check out the book module, you'll see an entry in the book_menu() hook (book/export/%/%) that uses the book_export() page callback. Examining that function leads you to book_export_html(). This function generates the html for printer-friendly layout using the book_export_traverse() function and then calls the theme() function. The theme function allows us to override the theme layer. In this example I'll create a function that follows the templates suggestions guidelines to insert my code...
<?php
// the first argument being passed to theme function is book_export_html, so I'll prefix my function with my theme's name
function MYTHEME_book_export_html($title, $contents, $depth) {
// since the node ID is not being passed as an argument,
// we'll grab it from the query string...
// load node
$node = node_load(arg(3));
// define a list of node types to override
$nodeTypes = array('MYCOMPLICATEDNODETYPE1','MYCOMPLICATEDNODETYPE2');
if (!in_array($node->type, $nodeTypes)) {
// for all the rest of my node types, I'll use the default template:
return theme('MYTHEME_book_export_html', $title, $contents, $depth);
}
// now, you have access to the $node variable and can do what ever you'd like with it
// note: the drupal_render() function is great for generating the output for a CCK field
return "MY NEW AMAZING PRINTER-FRIENDLY HTML";
}
?>
In the above code, the theme registry was overrode by creating a function named: MYTHEME_book_export_html. The last part of this code snippet is returning regular nodes back to the default book template file (book-export-html.tpl.php). In the above code, I mention a theme registry entry called "MYTHEME_book_export_html", which has not been registered yet. We can register a new template using hook_theme()...
<?php
function MYTHEME_theme() {
return array(
// register the default book export template
'MYTHEME_book_export_html' => array(
// pass it the same arguments, defined in the book_theme() function
'arguments' => array('title' => NULL, 'contents' => NULL, 'depth' => NULL),
// define the same template as defined in the book_theme() function
'template' => 'book-export-html',
// since this file does not exist in our theme directory,
// we'll specify the path of the book module
'path' => 'modules/book',
)
);
}
?>
Now that we've registered the "new" template (and rebuilt the theme registry) all of our standard nodes will use the original book template file and our custom node types will be modified as defined.