Django -- Template tag in {% if %} block

Randall Ma picture Randall Ma · Jul 7, 2012 · Viewed 123k times · Source

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.

Answer

Herman Schaaf picture Herman Schaaf · Jul 7, 2012

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 %}