I have a field (field_txt) that renders properly, but now i want to add a tag around it so that i can style the background color of it. How would this be possible using the preprocess field hook?


<div>some text value</div>

Desired Output:

<div><span class="bg-color-rd">some txt value</span></div>

1 Answer 1


Not sure how it would be done with a preprocess hook, but an alternative would be to instead copy field.tpl.php into your theme, rename it according to the convention of field-name-[field_name], and simply add the <span> and </span> elements at the appropriate points in the template, like so:

<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
    <span class="bg-color-rd">
        <?php if (!$label_hidden): ?>
        <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>:&nbsp;</div>
        <?php endif; ?>
        <div class="field-items"<?php print $content_attributes; ?>>
            <?php foreach ($items as $delta => $item): ?>
            <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><?php print render($item); ?></div>
            <?php endforeach; ?>
  • thank you for the suggestion. I did not use a field template override, but your suggesttion lead me down the path of writing a custom module to call hooK_preprocess_entity and hook_preprocess_field in which i was able to add the desired class using the #prefix and #suffix attributes. Sep 18, 2016 at 5:40
  • Good call. That's probably a cleaner way of doing it anyway.
    – Mrweiner
    Sep 18, 2016 at 8:36

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.