[development] Image Theming

Cameron B. Prince cplists at teslauniverse.com
Wed May 23 17:41:22 UTC 2012


I recently needed to insert an image from an image field into the node's body prior to rendering. I was able to do this using this code:

function THEME_preprocess_field(&$vars) {
  if ($vars['element']['#object']->type == 'case_study' && $vars['element']['#field_name'] == 'body') {
    $node = node_load($vars['element']['#object']->nid);
    $img = field_get_items('node', $node, 'field_cs_image');
    $img = field_view_value('node', $node, 'field_cs_image', $img[0], array(
      'type' => 'image',
      'settings' => array(
        'image_style' => 'list_image_large',
    $img = render($img);
    $vars['items'][0]['#markup'] = str_replace('alt=""', 'style="float:right;margin:0 0 20px 20px" alt="' . $node->title . '"', $img) . $vars['items'][0]['#markup'];

I don't like having to use the str_replace() function to specify attributes for the image but my efforts to use theme('image', ...) and theme('image_style', ...) were unsuccessful because they don't include width and height attributes.

I saw the big thread with Dave Reid on the performance issue with getsize(). I understand the reasoning for removing the function but how is it that rendering the image with field_view_value() produces an image tag with width and height attributes? Couldn't the theme functions use the same method?

Is there a better or more proper way to render an image with width and height attributes AND specify other attributes such as alt and style?


More information about the development mailing list