Description

In many cases we need a simple counter which increases on each dataset we get. Mostly in lists of nodes. We don't talk about the node id's or similar here. We talk about the simple position of the node in the list of the output. This is quite simple, but missing in core.

Attention

This documentation examples here will change the output of

print render($content);

Who to

If you want to show an increasing number on each listed node (for example in a frontpage of teasers) to maybe make it look like this:

1. Node
2. Node
3. Node
etc ...

... you can do it by a simple additional preprocess in the YOUR_THEME_NAME_preprocess_node() function in your template.php file (which can be found in your sites/all/YOURTHEME folder. If not, create the template.php file. It will hold your additional theming functions. More about that can be found in the docs.)

For numbered node teasers in D7 to get additional css class attributes it will look like this:

/**
 * Override or insert variables into the node template.
 */
function YOUR_THEME_NAME_preprocess_node(&$variables) {

  // Implementation of hook_preprocess_node to add node_depth_counter to every node.
    static $depths_counter;
    $variables['node_depth_counter'] = ++$depths_counter;
}

Step 2: Use the variable $node_depth_counter in your node.tpl.php file. For this example it would be here:

<div id="node-<?php print $node->nid; ?>" class="node-number-<?php print $node_depth_counter; ?> <?php print $classes; ?> clearfix"<?php print $attributes; ?>>

You should prevent using numbers as first letters in css classes.

Some Thoughts

If you ask me, this simple task should be included in core. We have sooo many css class attributes rendered already in D6 and 7, why we don't have a simple increasing number of the node counted when it gets rendered to the output for a page with more than one node? This would makes it possible to define css for every third or 10th node in the list (useful to clearfix in a magazine kind of template for example). I am sure this would be much easier and better performed by getting implementented in core than in prerocessing functions.

Comments

Fredj94’s picture

Thanks a lot !

I was good looking for this solution ;) I make it worked on Drupal 6 :)