Skyler
Skyler

Reputation: 420

Django template execute on only first occurance of match in a for loop

I have a video table with Foreign Keys that point to a document (multiple videos to one doc). I would like to check every element of that list, and on the first match with a query, enable an element (button that leads elsewhere). My attempts have been to use a for loop and then an if statement such that:

{% for vid in doc.video_set.all %}
    {% if vid.query_data == 'match_term' %}
    <-- button/link stuff -->
        {% initialize variable %}
    {% endif %}
{% endfor %}

the idea being if I initialized a variable I could add if "and variable is None" to the if statement and prevent future displays. However, after trying to use "set" and "with" to intialize variables I have been greeted with little more than error messages that seem to indicate these methods dont exist. How would I effectively achieve this functionality.

Upvotes: 0

Views: 337

Answers (1)

Alasdair
Alasdair

Reputation: 309029

Django template language does not allow you to set variables like this. Your question is a bit confusing because you are trying to show how you would implement it in the Django template, rather than showing what you want the template to display. Here's a couple of suggestions:

If match_term is constant, you could add a method to your model.

class Doc(models.Model):
    def first_match(self):
        return self.video_set.filter(query_data='match_term').first()

Then use {{ doc.first_match }} in the template.

If match_term changes, then you might have to write a custom template tag.

Upvotes: 1

Related Questions