我正在尝试在 django 模板中执行此操作:
{% for book in books %}
if book in this library
print "already in this library"
else
print "add to this library"
{% endfor %}
有两个库L
和O
。
但是同一本书可以在多个图书馆中,而我在图书馆 L
中。 b
这本书在两个图书馆中都有。这就是为什么我的循环同时提供两个输出的原因。
already in this library
add to this library
这是无稽之谈。我该如何修复这个逻辑?
最佳答案
所以有两种情况:
- a) 书在某个图书馆
- b) 这本书不在任何图书馆
我的建议是在 View 级别而不是在模板级别执行此操作:
- 编写一个 View 函数来计算两个列表:一个是不在图书馆的书,另一个是在某个图书馆的书。
- 将这两个数组合并到一个字典中(key = 书名,value = 表示该书是否在图书馆中的 bool 值)
- 将该词典发送到模板
关于python - 我怎样才能在 Django 模板中做到这一点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19958247/