I had a client ask me recently to help them identify the first and last nodes of a list view by adding a class to each of the list items.
This can be done pretty easily by overriding the appropriate views theme function and injecting some of our own code into the array of rendered nodes just before they are converted to a list and displayed.
Simply paste the snippet below into the file named template.php residing in your theme's folder. If there's no template.php, go ahead and create it.
One caveat: If you're already using the Views module's theme wizard to override the output of a list view, then this snippet will simply be ignored and you will lose the extra identifying information.
<?php
/**
* Override the default theme function for list views. The
* function has been copied from the views module and
* changed to add identifiers for each item of the list.
*
* Each list item will now have a class attribute in the
* format:
*
* list-node list-node-x
*
* Where x = the position of the item in the list.
*
* In addition, the first and last list items will be
* identified by class values of list-node-first and
* list-node-last respectively.
*
* IMPORTANT: If you use the Views Theme wizard this
* function will be bypassed and the class identifiers
* will be lost.
*
*/
function phptemplate_views_view_list($view, $nodes, $type) {
$fields = _views_get_fields();
$i = 0;
foreach ($nodes as $node) {
$item = '';
foreach ($view->field as $field) {
if (!isset($fields[$field['id']]['visible']) && $fields[$field['id']]['visible'] !== FALSE) {
if ($field['label']) {
$item .= "<div class='view-label ". views_css_safe('view-label-'. $field['queryname']) ."'>" . $field['label'] . "</div>";
}
$item .= "<div class='view-field ". views_css_safe('view-data-'. $field['queryname']) ."'>" . views_theme_field('views_handle_field', $field['queryname'], $fields, $field, $node, $view) . "</div>";
}
}
if ($i == 0) {
$items[$i]['class'] = 'list-node list-node-first list-node-1';
} elseif ($i == count($nodes) - 1) {
$items[$i]['class'] = 'list-node list-node-last list-node-' . count($nodes);
} else {
$this_node_count = $i + 1;
$items[$i]['class'] = 'list-node list-node-' . $this_node_count;
}
$items[$i]['data'] = "<div class='view-item ". views_css_safe('view-item-'. $view->name) ."'>$item</div>\n"; // l($node->title, "node/$node->nid");
$i++;
}
if ($items) {
return theme('item_list', $items);
}
}
?>