LondonUnderground
LondonUnderground

Reputation: 89

Optional html class in twig template

I have a simple reusable twig (generic.html.twig) template which look like:

<ul>
    {% for item in list %}
        <li>
            ...
        </li>
    {% endfor %}
</ul>

I use it many times in my code like this:

{% include "@Toto/generic.html.twig" with {"list": toto} %}

My problem is that I sometimes want to include a CSS class on the <ul> generated by my twig template. So sometimes I would like for it to render like this:

<ul class="myclass">

while other times I'd like for it to render without the class, like this:

<ul>

How do I implement optional classes in my twig template?

Upvotes: 0

Views: 3525

Answers (2)

Adib Aroui
Adib Aroui

Reputation: 5067

I would use something like:

{% include "@Toto/generic.html.twig" with {"list": toto, "status": true} %}

And check against status boolean

<ul {{ status ? 'class="myclass"' : '' }}>

Upvotes: 1

Frank B
Frank B

Reputation: 3697

I prefer the use of defined

<ul{% if ulClass is defined %} class="{{ ulClass }}"{% endif %}>
    {% for item in list %}
        <li>
            ...
        </li>
    {% endfor %}
</ul>

Upvotes: 2

Related Questions