I'm writing a field formatter and I need to override the default field formatting. I've already implemented themes for the items itself, but I can't get my theme to work for the field container.

I've set #theme in the following code, and my field-image.html.twig is found by Drupal and processed:

class ImageGalleryFormatter extends ImageFormatter {

   * {@inheritdoc}
  public function viewElements(FieldItemListInterface $items) {
    $elements = parent::viewElements($items);
    foreach ($elements as &$element) {
      $element['#theme'] = 'imagegallery_format';
    $elements['#theme'] = 'field_image';
    $elements['#attached']['library'][] = 'imagegallery_formatter/light-gallery';
    return $elements;


But it doesn't actually work correctly, I don't get any content for {{ item.content }}. This is the core of my field-image.html.twig:

{% for item in items %}
   <div>{{ item.content }}</div>
{% endfor %}

I suspect that I didn't implement hook_theme() correctly, I tried a few variants, but none worked.

function imagegallery_formatter_theme() {
  return array(
    'imagegallery_format' => array(
      'variables' => array('item' => NULL, 'item_attributes' => NULL, 'url' => NULL, 'image_style' => NULL),
    'igimage' => array(
    'variables' => array(
        'style_name' => NULL,
        'uri' => NULL,
        'width' => NULL,
        'height' => NULL,
        'alt' => '',
        'title' => NULL,
        'attributes' => array(),
      'field_image' => array(
        'render element' => 'element',),

The first two themes work, for those I simply copied the variables array from existing code. The third one doesn't work, and I couldn't find any existing code I could use as a template. I tried to define the variables instead of using 'render element', but I don't know how to define the items variable there. I tried setting it to NULL or an empty array, but nothing did work. When I put a variables array in hook_theme, I get simply four empty divs, with the render element array I get a single empty div.

What am I doing wrong here, and how do I override this theme correctly in my module?


I managed to track down the place in core where the code for this specific theme is located, it was in core/includes/theme.inc and not in the field or system module where I previously searched. Copying from there did work in the end, using render element in hook_theme() is correct, but I was missing an important preprocess function.

I defined the following function and called the original preprocess function from there:

function template_preprocess_field_image(&$vars, $hook) {
    template_preprocess_field($vars, $hook);
| improve this answer | |

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.