python - Django html for、if 等

标签 python html django tags

我正在尝试在 djnago-python 中对我的数据进行简单的 for 循环。

我想迭代一个列表并检查某个元素 x 是否具有特定的字段值。如果是这样,我想显示删除选项,如果不显示添加选项。

用普通语言来说应该是这样的:

flag = false
for x in list:
    if x.game == KNOWN_GAME:
        <show remove link>
        flag = true
        break
endfor
if flag == false:
    <show add link>

问题是我找不到正确的方法来做到这一点:没有中断,没有要创建的变量(标志),而且我不知道如何使用loop.last。

有什么建议或者我可以在哪里找到我想要的标签吗?

编辑 我在使用 View 内容时遇到问题。我的 KNOWN_GAME 来自 html 页面(来自某个 for 循环)。我有什么方法可以将它从 html 传递到 View 中的函数吗?

最佳答案

对于许多在模板中无法完成的事情,Django 的回答是在 View 中完成。

一般来说,任何复杂的逻辑都应该在 View 中完成。 Django 甚至不支持使用 flag=True 的方式声明变量。我们有 with 标签,但它定义的变量必须在定义 block 内使用。

查看

show_remove_link = False
if any(filter(lambda x: x.game == KNOWN_GAME, my_list)):
    show_remove_link = True

return render_to_response("mytemplate.html", {'show_remove_link': show_remove_link})

模板

{% if show_remove_link %}
    Show Remove Link
{% else %}
    Show Add Link
{% endif %}

关于python - Django html for、if 等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6389907/

相关文章:

CSS 没有加载错误的 MIME 类型 Django

python - 如何在 pandas 中选择没有弃用 ix 的多列

python - 分区(如果适用)

javascript - jQuery - 将类添加到不同数量的 div

django - Django模型中的列排序

python - django View 中导入错误?

python - 无法在 Django 中导入 View (2.1.4、Python 3.7.0、Win 7)

python - 发生错误时执行python

javascript - 我怎样才能从约会中得到一天

html - 导航位置 :fixed in right of the div