How to use if/else condition on Django Templates?

161,170

Solution 1

You shouldn't use the double-bracket {{ }} syntax within if or ifequal statements, you can simply access the variable there like you would in normal python:

{% if title == source %}
   ...
{% endif %}

Solution 2

Sorry for comment in an old post but if you want to use an else if statement this will help you

{% if title == source %}
    Do This
{% elif title == value %}
    Do This
{% else %}
    Do This
{% endif %}

For more info see https://docs.djangoproject.com/en/3.2/ref/templates/builtins/#if

Solution 3

{% for source in sources %}
  <tr>
    <td>{{ source }}</td>
    <td>
      {% ifequal title source %}
        Just now!
      {% endifequal %}
    </td>
  </tr>
{% endfor %}

                or


{% for source in sources %}
      <tr>
        <td>{{ source }}</td>
        <td>
          {% if title == source %}
            Just now!
          {% endif %}
        </td>
      </tr>
    {% endfor %}

See Django Doc

Solution 4

You try this.

I have already tried it in my django template.

It will work fine. Just remove the curly braces pair {{ and }} from {{source}}.

I have also added <table> tag and that's it.

After modification your code will look something like below.

{% for source in sources %}
   <table>
      <tr>
          <td>{{ source }}</td>
          <td>
              {% if title == source %}
                Just now! 
              {% endif %}
          </td>
      </tr>
   </table>
{% endfor %}

My dictionary looks like below,

{'title':"Rishikesh", 'sources':["Hemkesh", "Malinikesh", "Rishikesh", "Sandeep", "Darshan", "Veeru", "Shwetabh"]}

and OUTPUT looked like below once my template got rendered.

Hemkesh 
Malinikesh  
Rishikesh   Just now!
Sandeep 
Darshan 
Veeru   
Shwetabh    
Share:
161,170
Randall Ma
Author by

Randall Ma

Updated on July 05, 2022

Comments

  • Randall Ma
    Randall Ma almost 2 years

    I have the following dictionary passed to a render function, with sources being a list of strings and title being a string potentially equal to one of the strings in sources:

    {'title':title, 'sources':sources})
    

    In the HTML template I'd like to accomplish something among the lines of the following:

    {% for source in sources %}
      <tr>
        <td>{{ source }}</td>
        <td>
          {% if title == {{ source }} %}
            Just now!
          {% endif %}
        </td>
      </tr>
    {% endfor %}
    

    However, the following block of text results in an error:

    TemplateSyntaxError at /admin/start/
    Could not parse the remainder: '{{' from '{{'
    

    ...with {% if title == {{ source }} %} being highlighted in red.