0

I have a custom Entity called custom_entity, along with a custom module which provides twig templates for my bundles and their fields.

How can I define a generic/base field template for all fields created under custom_entity?

For a specific field I could create the template:

field--custom-entity--field-my-field.html.twig

But I'm looking to do something more general, like:

field--custom-entity.twig

Where all my fields created on a custom_entity use this base template.

I don't want to modify field.html.twig in the theme. I want this template to only apply to my entity and its bundles.

1

Add your own theme suggestion:

mymodule.module

/**
 * Implements hook_theme_suggestions_field_alter().
 */
function mymodule_theme_suggestions_field_alter(array &$suggestions, array $variables) {
  $element = $variables['element'];
  // place the least specific suggestion at the beginning of the array  
  array_unshift($suggestions, 'field__' . $element['#entity_type']);

}
| improve this answer | |
  • This worked if I implemented hook_theme in my custom module and pointed to the field__custom_entity template. However, then none of the fields would use their overridden field templates. For example, my_field would successfully use field__custom_entity.html.twig but would ignore field__custom_entity__my_field.html.twig. – John Aug 5 at 20:15
  • Yes, this makes sense to place the least specific suggestion at the beginning of the array so that the more specific suggestions have priority. See the edit. – 4k4 Aug 5 at 21:34
  • I unfortunately was not able to get this to work, despite array_unshift. I ended just creating templates specific to each field. – John Aug 12 at 19:14

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.