addClass in Twig with if statement in item-list.html.twig I try conditionally add a CSS class to a &lt;li&gt; element in item-list.html.twig.

{%- for item in items -%}

    {# check if is facet li #}
    {% if item.attributes.hasClass('facet-item') %}
    &lt;li{{ item.attributes.addClass('list-group-item') }}&gt;{{ item.value }}&lt;/li&gt;
    {% endif %} 

{%- endfor -%


When I add the if statement like above, I don't get any output at all. If I remove the if statement I get correct output like:

&lt;div class="item-list"&gt;           
    &lt;ul data-drupal-facet-id="contactvoorkeur" class="js-facets-checkbox-links list-group"&gt;
        &lt;li class="facet-item broodjeaap list-group-item"&gt;
            &lt;input type="checkbox" class="facets-checkbox" id="contactvoorkeur-email" data-facetsredir="/search-person/cards?f[0]=contactvoorkeur%3Aemail"&gt;
            &lt;label for="contactvoorkeur-email"&gt;E-mail &lt;span class="facet-count"&gt;(2)&lt;/span&gt;&lt;/label&gt;
            &lt;a href="/search-person/cards?f[0]=contactvoorkeur%3Aemail" rel="nofollow" data-drupal-facet-item-id="contactvoorkeur-email" style="display: none;"&gt;E-mail &lt;span class="facet-count"&gt;(2)&lt;/span&gt;
            &lt;/a&gt;
        &lt;/li&gt;          
    &lt;li class="facet-item broodjeaap list-group-item"&gt;
        &lt;input type="checkbox" class="facets-checkbox" id="contactvoorkeur-post" data-facetsredir="/search-person/cards?f[0]=contactvoorkeur%3Apost"&gt;
        &lt;label for="contactvoorkeur-post"&gt;Post &lt;span class="facet-count"&gt;(1)&lt;/span&gt;&lt;/label&gt;
        &lt;a href="/search-person/cards?f[0]=contactvoorkeur%3Apost" rel="nofollow" data-drupal-facet-item-id="contactvoorkeur-post" style="display: none;"&gt;Post &lt;span class="facet-count"&gt;(1)&lt;/span&gt;
        &lt;/a&gt;
    &lt;/li&gt;
  &lt;/ul&gt;
&lt;/div&gt;
I might be wrong here, as we do know know what problem you are having...

But {{ item.attributes.addClass('list-group-item') }} will add the list-group-item class to the item-element. (It does not print this class.)

Because of the surrounding code: {% if item.attributes.hasClass('facet-item') %} ... {% endif %}, I feel you want to add a class to the childs of item, not to item itself.

Why not output this instead? 

&lt;li class="list-group-item"&gt;{{item.value}}&lt;/li&gt;


So the condition becomes:

{% if item.attributes.hasClass('facet-item') %}
  &lt;li class="list-group-item"&gt;{{item.value}}&lt;/li&gt;
{% endif %}