Django — Template tag in {% if %} block

前端 未结 4 366
花落未央
花落未央 2020-12-16 08:51

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

相关标签:
4条回答
  • 2020-12-16 09:37

    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    
    
    0 讨论(0)
  • 2020-12-16 09:42

    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 %}
    
    0 讨论(0)
  • 2020-12-16 09:42

    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 Django Documentation

    0 讨论(0)
  • 2020-12-16 09:45
    {% 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

    0 讨论(0)
提交回复
热议问题