Score:0

Twig templates with lots of classes?

zw flag

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

Kevin avatar
in flag
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.
ru flag
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.
leymannx avatar
ne flag
I've seen many more. I like `attributes` arrays as they look much clearer than endless strings.
sonfd avatar
in flag
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.
john Smith avatar
gr flag
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
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.