Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
555 views
in Technique[技术] by (71.8m points)

drupal - How can I add a class to the attributes of a content item inside a twig template?

I've created a paragraph that has two fields, one is a video and the other is a text list. I want to change the classes on the video element, based on the result from the list field. One approach I could take is using if/elseif conditionals to assign the correct class to a variable and simply slot that into video markup I've typed out myself.

I was wondering though if there is a way to attach the generated class to the actual variable and then rendering it the normal way instead of manually typing out the markup. For example, instead of this:

{# paragraph.html.twig #}

{% set alignment-class %}
{% if content.field_alignment == 'left' %}
  {% alignment-class = 'align-left' %}
{% elseif content.field_alignment == 'center' %}
  {% alignment-class = 'align-center' %}
{% else %}
  {% alignment_class = 'align-right' %}
{% endif %}
<video {# manually add all the relevant attributes #}></video>

I could do some thing like:

{# paragraph.html.twig #}

{% set alignment-class %}
{% if content.field_alignment == 'left' %}
  {% alignment-class = 'align-left' %}
{% elseif content.field_alignment == 'center' %}
  {% alignment-class = 'align-center' %}
{% else %}
  {% alignment_class = 'align-right' %}
{% endif %}
{# add class to video attributes somehow #}
{{ content.field_video }}

Apologies if the syntax isn't exactly right, this is just an example. Anyway, adding the class from the media.html.twig template isn't possible, because I won't have access to the list field that determines what the class should be, so I have to work from the paragraph.html.twig as far as I know.

I know there is a top-level attributes variable I can add classes to, but that seems to be for the wrapper element of the whole paragraph. I've tried inspecting content.field_video with kint, but I can't seem to find a property that fits the bill. Is this approach possible?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...