I want to add the content of a field (i.e. "workshop") as a class in field-html.twig

i tried

  set classes = [
    'field--name-' ~ field_name|clean_class,
    'field--type-' ~ field_type|clean_class,
    'field--label-' ~ label_display,
    'icon-' ~ item.content,

but it only shows "icon-" as a class.

  • You know when you enable Devel's submodule Kint you can put {{ kint() }} to inspect variables onpage? – leymannx Nov 9 '19 at 15:01

item.content works only in the items loop, but don't try to put rendered output in a class name. Use the field value instead, which you can get through the field object #items stored in a field template inside of the variable element:

{{ element['#items'].value }}

or from a different field of the parent entity:

{{ element['#object'].field_example.value }}

Depending on the field type replace .value with a different property, for example for a reference field to get the target id or the label of the target with .target_id or .entity.label.

When you have found the field value build your class name:

  set classes = [
    'icon-' ~ element['#items'].value|clean_class,
| improve this answer | |
  • and how should i add this as a class? – jimi Nov 9 '19 at 16:26
  • replace the rendered output item.content with the field value: 'icon-' ~ element['#items'].value|clean_class, – 4k4 Nov 10 '19 at 11:21
  • thank you, but is gives "icon-array" – jimi Nov 11 '19 at 15:33
  • You didn't provide any details what field type this is. Can you provide a kint output of the variable to see what is in it? – 4k4 Nov 11 '19 at 16:04
  • it’s a taxonomy reference field. i’ll try give asap a kint output. thx. – jimi Nov 11 '19 at 20:10

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.