Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Multiple conditions for if statement in Jinja templates

Tags:

python

jinja2

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?

like image 536
Viktória Avatar asked Nov 23 '17 14:11

Viktória


People also ask

How do you do if statements in Jinja?

In-line conditional statements​ Jinja in-line conditionals are started with a curly brace and a % symbol, like {% if condition %} and closed with {% endif %} . You can optionally include both {% elif %} and {% else %} tags.

How do you define if condition in Nunjucks?

If. Nunjucks allows you to use if as an inline expression. For example: {{ "true" if var else "false" }} outputs the string "true" if the variable var is defined, else it outputs "false".

How do you write a for loop in Jinja?

For loops start with {% for my_item in my_collection %} and end with {% endfor %} . This is very similar to how you'd loop over an iterable in Python. Here my_item is a loop variable that will be taking values as we go over the elements.


1 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.

like image 53
akanxh2000 Avatar answered Oct 04 '22 02:10

akanxh2000