2

I have a content type with an image field; I would like to add CSS classes to those images.

I have looked at the values of the $content variable in node.tpl.php via the dpm(), but I couldn't see any properties/keys related to classes or attributes. Maybe I just couldn't see them, or I didn't know where to look.

I would like to print something like <img src="path-to-image" class="my-classes"> by using print render($content['myimage_field']) in node.tpl.php.

I do not want to use external modules to accomplish this. Is there any theme functions I can override? How do I override them?

3

You can use hook_node_preprocess in your themes template.php file to add to the 'attributes' array for the node before the variables are sent to your node template. when your field gets built up into html it will then have your class.

If you enable the devel module you can add the following to template.php to see what this 'build array' which is used to render the node looks like.

function twt_preprocess_node(&$vars) {

    dpm($vars);

}

To alter the classes added to your field use something like the following (though look to the above to find out if you are putting your class in the right place).

function twt_preprocess_node(&$vars) {

    $vars['field_myimagefield']['#attributes']['class'][] = 'myclass';

}

Some useful reading:

3

There is no such method available to apply classes directly from node.tpl.php You can achieve it by using theme function theme_image_style

e.g, in template.php

/**
 * Theme override
 * 
 * Add custom class to image styles
 */
function MY_THEME_image_style($variables) {
  // Determine the dimensions of the styled image.
  $dimensions = array(
    'width' => $variables['width'],
    'height' => $variables['height'],
  );

  image_style_transform_dimensions($variables['style_name'], $dimensions);

  $variables['width'] = $dimensions['width'];
  $variables['height'] = $dimensions['height'];

  // Determine the URL for the styled image.
  $variables['path'] = image_style_url($variables['style_name'], $variables['path']);

  /* Begin custom snippet */
  // Add or append custom classes, to avoid clobbering existing
  if (isset($variables['attributes']['class'])) {
    $variables['attributes']['class'] += array('my-class', $variables['style_name']);
  }else{
    $variables['attributes']['class'] = array('my-class', $variables['style_name']);
  }
  /* End custom snippet */
  return theme('image', $variables);
}

Note: This is just a clone of theme_image_style with the custom classes added at the end.

You can add some conditional logic based on style_name for specific classes, and also do a similar thing with theme_image if needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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