Python: Multiple conditions for if statement in Jinja templates

Viewed 34422

I got stuck in my coding project in jinja templates.

I want to show posts of a user just if 2 conditions are met:

The problematic part is if using and, conditions work perfectly individually but the moment I add and and join them together it does not work.

I have tried it with brackets and without them.

{% for post in posts %}

  {% if (session['user']['username']==post['author']) and (post["id"] | is_liked) %}

  {% else %}
    <li class="row">
      {% include "components/recommended.html" %}
    </li>
  {% endif %}
{% endfor %}

Could you please help me how to write that line, so that both conditions are checked?

2 Answers

Check this nested ifs (it suggests nested-ifs can be used how you would normally use them while writing native python code) and combining if conditions (multi-line if statements can be used as long as the code has parens/brackets around it)

Both of them work well.

came across the same problem and my solution looks like this:

{%- set test1 = '00:00' -%}
{%- set test2 = '00:00' -%}
{%- set test3 = '00:00' -%}
{%- set allconditionsmet = 'no' %}
{%- if test1 == '00:00' -%}
{%-   if test2 == '00:00' -%}
{%-     if test3 == '00:00' -%}
{%-       set allconditionsmet = 'yes' %}
{%-     endif -%}
{%-   endif -%}
{%- endif -%}
{%- if allconditionsmet == 'yes' -%}
{{    'all conditions met' }}
{%- else -%}
{{    'some conditions not met' }}
{%- endif -%}

you could also use a bool or an int or whatever you like as the allconditionsmet. maybe you make it an int and count up, then you can determine if 5 of 7 conditions are ok. whatever floats your goat.

Related