Search code examples
symfonytwigoctobercmscraftcms

How can I check multiple if conditions in twig?


How can I check multiple if conditions in twig? Neither of these seem to work Also they all seem a but messy and heavy.

  {% if pageClass != "page-home" %}
  {% if bodyClass != "500" %}
  {% if bodyClass != "404" %}
         {% include '_components/type-bg' with {
                    content: {
                        slug: entry.slug|split(' ')|slice(0, 1)|join
                    },
                } only %}
   {% endif %}
   {% endif %}
   {% endif %}

I have also tried the below

    {% if (pageClass != "page-home") or (if bodyClass != "500") or (if bodyClass != "404")%}

      {% include '_components/type-bg' with {
                    content: {
                        slug: entry.slug|split(' ')|slice(0, 1)|join
                    },
                } only %}

    {% endif %}

Solution

  • You need to use and as your all condition need to satisfy to execute that code so it must be and

    {% if pageClass != "page-home" and bodyClass != "500" and bodyClass != "404" %} 
         {% include '_components/type-bg' with {
             content: {
                 slug: entry.slug|split(' ')|slice(0, 1)|join
             },
         } only %}   
    {% endif %}
    

    Better solution would be from code block just use PHP code [you can do all PHP stuff here] to achieve this using switch case or etc .. and pass only flag like needToInclude as boolean to view and just use that.

    enter image description here

    {% if needToInclude %} 
         {% include '_components/type-bg' with {
             content: {
                 slug: entry.slug|split(' ')|slice(0, 1)|join
             },
         } only %}   
    {% endif %}
    

    if any doubt please comment