Sac*_*hin 20 django django-templates
我的模板中有以下代码
{% 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 %}
Run Code Online (Sandbox Code Playgroud)
我使用此自定义标记设置变量的值,我想要做的是仅在if满足循环时增加值.我知道{{counter++}}不起作用.但是,如何编写可以执行相同任务的自定义标记?
Edu*_*nec 29
不鼓励更改Django模板中对象的状态.您应该咬紧牙关,事先计算条件并将额外状态传递给模板,这样您就可以简化模板逻辑.
顺便说一下,我并不是这方面的纯粹主义者,但我已经被Django模板的有目的限制所困扰了几次.在我看来,你最好不要反对它.
由于你的意图似乎是过滤掉不匹配的项目,另一种方法是过滤掉视图中的那些,然后{{ forloop.counter }}用来整理你想要的链接文本.所以在视图中你有这样的东西:
new_lst = filter(lambda x: x.attr0 == attr0 and x.attr1 == attr1, lst)
Run Code Online (Sandbox Code Playgroud)
然后,在您的模板中:
{% for object in new_lst %}
<li><a href="{{ object.get_absolute_url }}"> Link {{ forloop.counter }} </a></li>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
T I*_*T I 12
虽然这已经得到了回答并且违背了我所说的,我只是想了一下,如果你做了简单的计数器课,就不会看到太多的伤害
class Counter:
count = 0
def increment(self):
self.count += 1
return ''
def decrement(self):
self.count -= 1
return ''
def double(self):
self.count *= 2
return ''
Run Code Online (Sandbox Code Playgroud)
然后在你的模板{{ counter.increment }} {{ counter.count }}等
为了增加模板 django 中的值:如果 varint=6,结果将为 8
{{ varint|add:"2" }}
Run Code Online (Sandbox Code Playgroud)
为了减少模板 django 中的值:
如果 varint=6,结果将为 5
{{ varint|add:"-1" }}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
33004 次 |
| 最近记录: |