Using HTML5 figure & figcaption elements to markup Image fields in Drupal 7

I've been reading up about the figure and figcaption elements for HTML5 over at the HTML5 Doctor and other places and thought I'd use these new elements to create captioned images in Drupal 7.

This is actually so easy its not funny, in fact you only need to make one configuration change to your image field and add one template override and you're done.

First - edit your image field settings and check the option to Enable Title field. We're going to re-use the title field to add our captions.

Next create a new template in your theme called field--image.tpl.php. Actually you can use whatever suggestion you want, for example you might only want this to apply to one particular image field, in which case you can use the field name suggestion, such as field--field-myimage.tpl.php.

Paste this into that new template file:

<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if (!$label_hidden) : ?>
    <h2 class="field-label"<?php print $title_attributes; ?>><?php print $label ?>:&nbsp;</h2>
  <?php endif; ?>
  <?php foreach ($items as $delta => $item): ?>
    <figure class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>>
      <?php print render($item); ?>
      <?php if ($item['#item']['title']): ?>
        <figcaption><?php print $item['#item']['title']; ?></figcaption>
      <?php endif; ?>
  <?php endforeach; ?>

This will print each image wrapped in the <figure> element and if you add a title to the image (done when you upload your pic) a caption will be added below the image in the <figcaption> element.

I'm toying with the idea of adding this to Adaptivetheme (the Drupal 7 version is HTML5) as the default field-image.tpl.php template, but I'll probably wait a little bit to see if <figcaption> sticks around, theres been a fair bit of debate over it so its a wait and see game at them moment.

Last updated 17th August, 2011 - 10:27pm

Authored by Jeff Burnz on