开发者

Dynamic session access in templates

开发者 https://www.devze.com 2023-03-24 08:21 出处:网络
I\'m trying to access session keys within a lo开发者_如何学运维op that needs to be dynamic, I think you\'ll get what I\'m going for by looking at my code that isn\'t working.

I'm trying to access session keys within a lo开发者_如何学运维op 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 %}


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号