Reputation: 89
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
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
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