简体   繁体   中英

Control flow in Django template language

I have the following code, written inside a Django template.

{% if user.is_authenticated %}
    <div style="float: right;">
    {% for rel in RELATIONS %}
        {% if rel.group_id == g.id %}
            <a href="/group/{{ g.id }}/unsubscribe/" class="form-button">Unsubscribe</a>
        {% endif %}
    {% else %}
        <a href="/group/{{ g.id }}/subscribe/" class="form-button">Enrol</a>
    {% endfor %}
    </div>
{% endif %}

The purpose of the code is to check if there is a match and then print out the unsubscribe tag. If there is not match print out the subscribe tag.

The reason I am having trouble doing this is because you in Django templates, I read that you can't have variables (ie a True or False).

UPDATE: (The question)

I want to only print out the Unsubscribe/subscribe button once. Print out the unsubscribe button only if there is a match inside the for loop. Otherwise print out the subscribe button if there is no match (ie no match at all for rel.group_id == g.id )

UPDATE 2:

While doing some research earlier I found this: https://code.djangoproject.com/ticket/3481 This might add some context to my problem.

Thank you for your help.

Seems like your if/else/endif are mixed up. Try

{% if user.is_authenticated %}
    <div style="float: right;">
    {% for rel in RELATIONS %}
        {% if rel.group_id == g.id %}
            <a href="/group/{{ g.id }}/unsubscribe/" class="form-button">Unsubscribe</a>
        {% else %}
            <a href="/group/{{ g.id }}/subscribe/" class="form-button">Enrol</a>
        {% endif %}
    {% endfor %}
    </div>
{% endif %}

UPDATE

You want to check if g is in relations and make your decission based upon that.
The way I usually solve this is to create a function in my view that does this check and passes that allong to the view. Have a look here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM