Member-only story
Using the new add_suggestion Twig filter in Drupal 10
When building my wife’s web store, I used a new feature in Drupal 10 when templating her product display pages. Drupal 10 introduced a new Twig filter called add_suggestion
. Drupal's render array output is templated through Twig and provides a base template name and more refined alternatives for controlled templating. Here's a list of template suggestions for outputting an image field from a product entity, from the most generic to the most specific.
field.html.twig
: The default for all fieldsfield--entity-reference.html.twig
: The default for all entity reference fields.field--field-images.html.twig
: The default for fields with this name (across all entity types and bundles.)field--commerce-product.html.twig
: The default for all fields of this entity type (commerce_product
.)field--commerce-product--cookie-set.html.twig
: The default for all fields of this entity type (commerce_product
) and bundle (cookie_set
.)field--commerce-product--field-images.html.twig
: The default for fields with this name for this entity type (commerce_product
)field--commerce-product--field-images--cookie-set.html.twig
: The default for fields with this name for this entity type (commerce_product
) and bundle (cookie_set
.)
Many times, developers need to customize the output for a field but not for every instance. In my use case, all products have a media field for…