Thursday, September 22, 2011

Overriding other theme functions

If you want to override a theme function not included in the basic list (block, box, comment, node, page), you need to tell PHPTemplate about it.
To do this, you need to create a template.php file in your theme's directory. This file must start with a PHP opening tag <?php but the close tag is not needed and it is recommended that you omit it. Also included in the file are stubs for the theme overrides. These stubs instruct the engine what template file to use and which variables to pass to it.
First, you need to locate the appropriate theme function to override. You can find a list of these in the API documentation. We will use theme_item_list() as an example.
The function definition for theme_item_list() looks like this:
<?php
function theme_item_list($items = array(), $title = NULL) {
$output = '<div class="item-list">';
if (isset($title)) {
$output .= '<h3>'. $title .'</h3>';
}

?>
Now you need to place a stub in your theme's template.php, like this:
<?php
/**
* Catch the theme_item_list function, and redirect through the template api
*/
function phptemplate_item_list($items = array(), $title = NULL) {
// Pass to phptemplate, including translating the parameters to an associative array.
// The element names are the names that the variables
// will be assigned within your template.
return _phptemplate_callback('item_list', array('items' => $items, 'title' => $title));
}

?>
We replaced the word theme in the function name with phptemplate and used a call to _phptemplate_callback() to pass the parameters ($items and $title) to PHPTemplate.
Now, you can create a file item_list.tpl.php file in your theme's directory, which will be used to theme item lists. Start by putting in the code from the original theme_item_list(). Do not wrap this code into a function, write inline, e.g.
<?php
$output = '<div class="item-list">';
if (isset($title)) {
$output .= '<h3>'. $title .'</h3>';
}

?>

No comments:

Post a Comment