Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

Adding first and last classes to your field items

Parent Feed: 

By default, Drupal's core field.module with add 'odd' and 'even' classes to your field items, but it won't add 'first' and 'last' classes! This can quickly be remedied by overriding the core field.tpl.php file with your own custom one.

I'd recommend first copying /modules/field/theme/field.tpl.php into your site's theme folder. For me, the destination was /sites/all/themes/grasmash/templates/field.tpl.php. Then clear your caches. This will force Drupal to check for new template files in your theme's directory, and select the new field.tpl.php as the prioritized template for generating fields.

Here's the business part of my customized field.tpl.php file:

clearfix">

>

> $item): ?>

">

There are two important changes here:

  • counts the total number of field items in each field, allowing us to determine which field item should be given the 'last' class
  • will print out our new sparkly classes.

You should note that this may add a small performance tax to your site by requiring PHP to count the $items array for every field, but I think that it is fairly negligible. Some people would prefer not to include this kind of logic in a template file at all. Let me know if you've got a better way!

Author: 
Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web