Drupal 7 Theming and the image Path

In Drupal 7 there is a filefield in core now, there is also something like imagecache in Drupal 6 called image styles.

When it comes to theming you will soon find out that the image data stored in the node array is completely different than before. For example there is no filepath available.

Display image fields in templates

First and recommended solution would be to display the field as it is with the render() function:

<?php
  print render($content['field_name']);
?>

 
But for doing some more customization (e.g. for a special image slider) you might need the path to the image.
This is not as easy as in Drupal 6, because the path is not available in the node object any more. So one handy solution is to use image_style_url() to get the path:

<?php
  $field_items = field_get_items('node', $node, 'field_image');
  $path = image_style_url('image_style_name', $field_items[0]['uri']);
?>

 
This is already the path to the formatted image. So you can display the image with theme_image() now.

theme_image()

In addition the theme_image function to output images has changed too:

<?php
  $output = theme('image', array('path' => path_to_theme() . '/images/picture.gif'));
?>

 

Notice that the variables have to be specified in a single array now. You can read more about this at http://api.drupal.org/api/function/theme_image/7.

<?php
  $field_items = field_get_items('node', $node, 'field_image');
  $output = theme('image', array('path' => $field_items[0]['uri']));
?>

 

theme_image_formatter()

Another solution is the theme_image_formatter function, that does some of the stuff for you:

<?php
 $field_items = field_get_items('node', $node, 'field_image');
  $var = array(
    'item' => $node->field_items[0],
    'image_style' => 'image_style_name'
  );
 
  $output = theme_image_formatter($var);
?>

 

Links:

http://api.drupal.org/api/function/theme_image/7
http://api.drupal.org/api/function/image_style_url/7
http://api.drupal.org/api/function/theme_image_formatter/7
http://api.drupal.org/api/function/field_view_value/7
http://api.drupal.org/api/function/field_view_field/7
http://api.drupal.org/api/function/render/7





Powered by Drupal7