Score:1

How to use field value to set custom class and apply it to a html element in node.html.twig without using attributes and addClass()

tr flag

I have tried to apply my custom class to an image tag

I have set classes for it

{% set imgClass = [
        'img-shape-' ~ (node.field_image_animation_shape.value|clean_class)
      ] %}

and have tried to apply to image as attributes

 attributes.addClass(imgClass)

that is renders all attributes for the node which duplicating on main node div so i need to avoid using attributes... How do i do it?

Score:3
ne flag

You simply create your own attributes. Read [Documentation] Using attributes in templates. It's much easier to maintain in the long run. Especially if you start to use conditions to add or remove attributes.

This provides a new blank Attribute object to use to build up attributes.

{% set my_attribute = create_attribute() %}
{%
  set my_classes = [
    'kittens',
    'llamas',
    'puppies',
  ]
%}
<div{{ my_attribute.addClass(my_classes).setAttribute('id', 'myUniqueId') }}>
  {{ content }}
</div>
Score:0
tr flag

I have workaround this without using attributes and that how i did it:

 {% set imgClass = node.field_image_animation_shape.value|clean_class %} 

created variable from the list text field - used key value for it

and then printed in hard way in to image classes

<img class="img-fluid img-shape-{{ imgClass }}" src="..." />

and this is result :

enter image description here

hope it will help to anybody :)

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.