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?