Drupal: How to Format Text of a Teaser
In this article, I would tell you how to format text of a teaser in a theme template (node.tpl.php). I propose you two different ways to do this. They are applicable for Drupal 5 and for Drupal 6.
Solution
Drupal 5
In this version, teaser text is a variable of $node object:
echo $node->teaser;
Drupal 6
In D6, $node doesn’t contains a variable with a text of a teaser because of different mechanism of teasers working.
When a template gets these nodes, there are only $body and $content. $content contains teaser only (when view of the list of articles) or a text of a node (in full view). A teaser is never created as a single variable when full view of a node text.
Let’s use theme_name_preprocess_node() to define if a teaser was set manually and if "Show teaser in full view" parameter is disabled. When "Show teaser in full view" is enabled, Drupal automatically adds a teaser to $body (or $content) of a node.
function phptemplate_preprocess_node(&$variables) {
if ($variables[‘page’] == TRUE) {
$node = node_load($variables[‘nid’]);
if (strpos($node->body, ‘<! –break– >’) === 0) {//Remove spaces
$variables[‘style_teaser_differently’] = TRUE;
$variables[‘only_teaser’] = check_markup($node->teaser, $node->format, FALSE);
}
}
}
Note:
The node was uploaded earlier and node_load() will return a cached version.
Output to node.tpl.php
<?php if ($style_teaser_differently) { ?>
<div class="node-summary"><?php print $only_teaser; ?></div>
<?php } ?>
Note:
You should clear cache on "Performance" page (admin/settings/performance). Otherwise the changes will not be applied to template.php.