0

I'm trying to access session keys within a loop that needs to be dynamic, I think you'll get what I'm going for by looking at my code that isn't working.

{% for q in questions %}
<div class="question_wrap">
    <h2>{{ q }}</h2>

    # this does not work
    {% if not request.session.get(str(q.id), False) %}
        <!-- show them vote options -->
    {% else %}
        <!-- dont show options -->
    {% endif %}

</div>
{% endfor %}
jondavidjohn
  • 61,812
  • 21
  • 118
  • 158

1 Answers1

2

The syntax of Django templates is very limiting in order to prevent people from putting too much logic inside templates and doesn't allow you to pass parameters to methods.

You can prepare a list of tuples already in the view or write a simple template tag for that. The first options is usually easier:

In the view:

questions = [(q, request.session.get(str(q.id), False)) for q in questions]

In the template:

{% for q, has_voted in questions %}
...
{% endfor %}
Jakub Roztocil
  • 15,930
  • 5
  • 50
  • 52
  • thanks, could you clarify exactly what the `view` code is doing? – jondavidjohn Jul 31 '11 at 20:51
  • It creates a list of tuples where the first element is a question and the second one is a `bool` indicating whether there was a value in the session object for the question's id, eg: `[(q1, False), (q2, True), ...]`. The syntax is called 'list comprehensions' in Python (http://docs.python.org/tutorial/datastructures.html#list-comprehensions). – Jakub Roztocil Jul 31 '11 at 21:00