0

I have created a twig template and have added classes like below.

{%
  set title-classes = [
    'title',
    'h1',
  ]
%}

{%
  set subtitle-classes = [
    'subtitle',
    'h2',
  ]
%}

<div{{ attributes.addClass('title-classes') }}>
    {{ content.title }}
</div>
<div{{ attributes.addClass('subtitle-classes') }}>
    {{ content.field_subtitle }}
</div>

What do I do when I have a complex HTML template. Consider the below. This is a very small section of my node type. Should I create classes for all of the different classes I use? Or can I just put them as I have below?

<div class="section highlighted">
    <div class="title h1">
        {{ content.title }}
    </div>
    <div class="subtitle h2">
        {{ content.field_subtitle }}
    </div>
    <div class="panel intro padding-lg">
        <p>{{ content.field_intro }}</p>
        <p class="disclaimer">{{ content.field_intro_disclaimer }}</p>
        <a href="{{ content.field_link }}" class="btn inline padding-lg hide-small">{{ content.field_link_text }}</a>
        <a href="{{ content.field_link_2 }}" class="btn block hide-large hide-medium">{{ content.field_link_text_2 }}</a>
    </div>
</div>

Whats the best way to create twig templates that use lots of different classes/attributes? Thanks

5
  • 1
    You can create as many attributes as you want. But if these classes aren't coming from anywhere in the CMS or the template never changes, it just seems like overkill.
    – Kevin
    Jan 19, 2022 at 15:13
  • 1
    You can create as many additional <div> wrappers and classes and attributes as you want. BUT: Omitting the default attributes can cause problems with frontend editing or any forms in general (this includes comments or views with paging/filters). As long as you only edit stuff/submit form data in admin theme only, it doesn't really matter.
    – Hudri
    Jan 19, 2022 at 15:25
  • I've seen many more. I like attributes arrays as they look much clearer than endless strings.
    – leymannx
    Jan 19, 2022 at 15:50
  • I personally would not want to define arrays of classes for every element at the top of my template. I think it would make it much more difficult to maintain. For the main wrapper, sure.
    – sonfd
    Jan 19, 2022 at 16:26
  • in my opinion you would mainly use drupals-twig-attributes for everything that involves dynamic serverside logic, if you have elements with no dynamic values at all i dont see the point
    – john Smith
    Jan 21, 2022 at 8:06

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.