Print a Picture Element in Drupal's Theme Layer Using theme_picture

Often, Drupal themers will hard-code images into a theme's template files (e.g. a site logo). In the era of responsive images, we now have the Picture module to handle the complexity that comes with responsive images. A themer can print a responsive site logo; it will just take a little more code.

Theming with Images before Responsive Images

Before responsive images, Drupal themers could print an image in a template file by 1) simply hardcoding an image element or 2) by using the theme_image function.

To use the theme_image function, the themer would simply need to pass the function an array describing the image to be rendered:

<?php
$image_array
= array(
 
'path' => '/sites/all/themes/mytheme/images/logo.jpg',
 
'alt' => 'Alternate Text',
 
'title' => 'Image Title',
 
'width' => '100px',
 
'height' => '100px',
 
'attributes' => array(
   
'class' => 'logo-img',
   
'id' => 'site-logo'),
);
print
theme('image', $image_array);
?>

Theming with Responsive Images

It's not well documented at the moment, but the Picture module provides a theme_picture function, which works similarly to the theme_image function. The major difference is that the developer must load the breakpoints for a picture mapping before calling the theme_picture function.

In the example below, the machine name of the Picture mapping to be used is 'logo':

<?php
// Load picture mapping from mapping name.
$picture_mapping = picture_mapping_load('logo');
// Load breakpoints for picture mapping.
$breakpoints = picture_get_mapping_breakpoints($picture_mapping);

$picture_array = array(
 
'style_name' => 'logo',
 
'uri' => '/sites/all/themes/mytheme/images/logo.jpg',
 
'alt' => 'Alternate Text',
 
'title' => 'Image Title',
 
'width' => '100px',
 
'height' => '100px',
 
'breakpoints' => $breakpoints,
 
'attributes' => array(
   
'data-picture-mapping' => 'logo',
   
'data-picture-align' => 'right',
   
'class' => 'logo-img',
   
'id' => 'site-logo',
   ),
 
// Set timestamp to prevent notice.
 
'timestamp' => NULL,
);
print
theme('picture', $picture_array);
?>

The breakpoints code can also be condensed:

<?php
-   'breakpoints' => $breakpoints,
+  
'breakpoints' => picture_get_mapping_breakpoints(picture_mapping_load('logo')),
?>

Add new comment