Django 模板 - 增加变量的值 [英] Django Template - Increment the value of a variable

查看:19
本文介绍了Django 模板 - 增加变量的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模板中有以下代码

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

我使用这个自定义标签来设置变量的值以及我想要做什么是仅在满足 if 循环时才增加值.我知道 {{counter++}} 不起作用.但是,我如何编写可以完成相同任务的自定义标记?

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?

推荐答案

不鼓励在 Django 模板中更改对象的状态.您可能应该咬紧牙关,预先计算条件并将额外的状态传递给模板,以便您可以简化模板逻辑.

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.

顺便说一下,我在这方面并不是纯粹主义者,但我曾几次被 Django 模板的有意限制所困扰.在我看来,你最好不要反对它.

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.

由于您的意图似乎是过滤掉不匹配的项目,另一种方法是过滤掉视图中的项目,然后使用 {{ forloop.counter }} 整理出你想要的链接文字.所以在视图中你有这样的东西:

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)

然后,在您的模板中:

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

这篇关于Django 模板 - 增加变量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆