What's the best way to alter html of an image field? I have imagefield and i want to rewrite it's html from scratch.

  • Some more detailed information on the markup changes you want to do would allow people to give you a more accurate answer. – rooby Mar 9 '14 at 3:00

hook_preprocess_HOOK will do the job,

You may also take a look at writing your own theme_image_formatter()

It could work in a node_view() but you want to alter the FIELD's HTML.In node_view you would alter the order of fields, hide/show new contents NOT control how they look.. you could absolutely do it, but it will not be the best/Drupal way.

Drupal divides functionality (node_view()) and looks (theme)

In a hook_preprocess_node() you would alter the node template variables, not the field's ones.You would need it to add a class to a node wrapper, to change node templates etc... you have to go deeper in the theme for this one.


// ALL IMAGES get rounded class.
function YOURTHEME_preprocess_image(&$variables) {
  $variables['attributes']['class'] = array('rounded');

and for field

// If field_images in FULL view mode of a node, add/edit variables and choose template
function YOURTHEME_preprocess_field(&$variables) {
  if ($element['#field_name'] == 'field_images' && $element['#bundle'] == 'YOUR_NODE_TYPE' && $element['#view_mode'] == 'full') {
 $variables['theme_hook_suggestions'][] = 'field__field_images_YOUR-file-name';
  // Add more variables available in template...
  $variables['toggle'] = 'Read the story';
  $variables['some_text'] = 'Some text';

  • Image is theme_image() not image.tpl.php so you can't do hook_reprocess_image() out of the box. – rooby Mar 8 '14 at 11:29
  • you can hook to any theme hook with hook_preprocess_HOOK, whats the template got to do with it? – Pan Chrono Mar 8 '14 at 11:36
  • Why hook_node_view() won't work? – Alexander Kim Mar 8 '14 at 11:40
  • Answered your comment in my answer – Pan Chrono Mar 8 '14 at 12:16
  • Oh whoops sorry, I don't know why I thought that. It's still possibly not as useful to the OP as overriding theme_image(), although we don't really have any information on what the markup changes are so we can't really know. – rooby Mar 9 '14 at 2:59

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.