8

In a template file, before print render($content['field_image']); I would like to add a CSS class to the image in the $content['field_image'] render array. How can I do this? Here is the render array:

Array
(
[#theme] => field
[#weight] => 2
[#title] => Image
[#access] => 1
[#label_display] => hidden
[#view_mode] => full
[#language] => und
[#field_name] => field_image
[#field_type] => image
[#field_translatable] => 1
[#entity_type] => node
[#bundle] => ll_basic_page
[#object] => stdClass Object
[#items] => Array
    (
        [0] => Array
            (
                [fid] => 6777
                [alt] => alt text
                [title] => 
                [uid] => 1
                [filename] => imageFile.jpg
                [uri] => public://imageFile.jpg
                [filemime] => image/jpeg
                [filesize] => 28742
                [status] => 1
                [timestamp] => 1314312382
                [rdf_mapping] => Array
                    (
                    )
            )
    )
[#formatter] => image
[0] => Array
    (
        [#theme] => image_formatter
        [#item] => Array
            (
                [fid] => 6777
                [alt] => alt text
                [title] => 
                [uid] => 1
                [filename] => imageFile.jpg
                [uri] => public://imageFile.jpg
                [filemime] => image/jpeg
                [filesize] => 28742
                [status] => 1
                [timestamp] => 1314312382
                [rdf_mapping] => Array ()
            )
        [#image_style] => 
        [#path] => 
    )
)

And this is the HTML output:

<div class="field field-name-field-image field-type-image field-label-hidden" thmr="thmr_96">
  <div class="field-items">
    <div class="field-item even">
      <span thmr="thmr_97">
        <span thmr="thmr_98">
          <img typeof="foaf:Image" src="http://..../sites/default/files/imageFile.jpg" alt="alt text" />
        </span>
      </span>
    </div>
  </div>
</div>

I tried adding a class to $content['field_image']['#attributes']['class'], but that didn't work.
Do you have any idea on how I can achieve what I am trying to do?

7 Answers 7

7

I believe it would be:

$content['field_image'][0]['#attributes']['class'][] = 'my-class';

Or to assign it to every element,

foreach (element_children($content['field_image'] as $key) {
  $content['field_image'][$key]['#attributes']['class'][] = 'my-class';
}
2
  • 1
    Tried this but doesn't work.
    – dazz
    Feb 15, 2012 at 14:14
  • 1
    Which part? The first or the second? Because both actually work. Feb 16, 2012 at 2:05
4

The above solutions did not work for me (and weren't clearly described in any case). Here's the way I solved this exact problem. This is probably not the best way, and certainly not the only, but it's a valid "Drupal way" and works. Open up the template.php file for your template.

Paste in the following function, which you will have to MODIFY and customize for your usage scenario. For example, you must replace <TEMPLATENAME> with your template name, and add or subtract classes as desired, and other things, as you'll see.

function <TEMPLATENAME>_preprocess_image(&$variables) {
    // If this image is of the type 'Staff Photo' then assign additional classes to it:
    if ($variables['style_name'] == 'staff_photo') {
        $variables['attributes']['class'][] = 'lightbox';
        $variables['attributes']['class'][] = 'wideborder';
    }
}

I created an "if" statement to determine when the class should be added to the image, but you will have to customize that however you like--you might eliminate it entirely if you want a class on ALL image-field images, or you might say if (drupal_is_front_page()) if you only want it applied on the front page, etc.

In MY case, I created an image style (Configuration > Media > Image Styles) for Staff Photos and added the if clause to only apply my preferred classes to images of that specified Image Style. I think that's a great way to do it, but you can do what you like.

Now, whenever I am viewing a node which contains an image-field with image style of "Staff Photo," the classes magically appear in the IMG tag, which is just what I needed.

3

This issue seems fixed in core 7.23

In the node tpl add this at the top:

<?php
$content['field_name'][0]['#item']['attributes']['class'][] = 'your-class';
?>
1
  • This works for field_type=image.
    – cweiske
    Jan 12, 2021 at 9:26
2

You can also do something like this:

  $array['container']['#prefix'] = '<div id = "container">';
  $array['container']['#suffix'] = '</div>';
1
  • 2
    In this case, you'd be better off with '#type' => 'container' and the #attributes method above, rather than hardcoding the div and class, because then nothing can add to the class, defeating the purpose of a renderable array. Oct 17, 2011 at 8:28
1

For those of you in a "field--field-image.tpl.php," use this:

$item['#item']['#attributes']['class'][] = 'your-class';
0

I was looking for a similar solution, but for styling a form input element and not an image. Inside my customized commerce_coupon.checkout_pane.inc include i added an #attributes array containing the necessary classes.

So if you're looking for a module entangled solution instead of template embedded, this might be a good alternative.

Running on Drupal 7.39

  $pane_form['coupon_add'] = array(
    '#type' => 'button',   
    '#value' => t('Add coupon'),    
    '#name' => 'coupon_add',    
    '#limit_validation_errors' => array(),    
    '#ajax' => array(    
      'callback' => 'commerce_coupon_add_coupon_callback',    
      'wrapper' => 'commerce-checkout-coupon-ajax-wrapper',    
    ),
    '#attributes' => array('class' => array('btn', 'btn-13')),
0

If you need some conditions to apply the class, you'll need to gather page fields informations.

You can do it with function template_preprocess_field(&$variables).

template_preprocess_field(&$variables) {
  if ($variables['element']['#field_type'] == 'image') {
        $variables['items'][0]['#item']['attributes']['class'][] = 'your-class';
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.