Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
869 views
in Technique[技术] by (71.8m points)

Django Template - Increment the value of a variable

I have the following code in my template

{% set counter = 0 %}
{% for object in object_list %}
    {% if object.attr1 == list1.attr1 and object.attr2 = list2.attr2 %}
        <li><a href="{{ object.get_absolute_url }}"> Link {{counter++}} </a></li>
     {% endif %}
{% endfor %}

I setting the value of a variable using this custom tag and what I want to do is to increment the value only if the if loop is satisfied. I know {{counter++}} does not work. But how can I write a custom tag that would do the same task?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Changing the state of an object in a Django template is discouraged. You should probably bite the bullet, calculate the condition beforehand and pass extra state to the template so you can simplify the template logic.

I'm no purist in this regard by the way, but I have been bitten by the purposeful limitations of Django templates a few times. You're better off not fighting against it, in my opinion.

Being that your intention seems to be to filter out non-matching items, an alternative would be to filter out those in the view and then use {{ forloop.counter }} to sort out the link text you want. So in the view you have something like this:

new_lst = filter(lambda x: x.attr0 == attr0 and x.attr1 == attr1, lst)

And then, in your template:

{% for object in new_lst %}
   <li><a href="{{ object.get_absolute_url }}"> Link {{ forloop.counter }} </a></li>
{% endfor %}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...