如何使用模板标签在django模板中创建临时列表?
如果无法在django模板中创建临时列表,那么如何使用模板标签来修复下面的场景呢?
简单的故事:我有一个名为 Info 的列表,它包含一堆重复值(例如“hi”,“hello”,“hi”,“hello”, “HEJ”, “哎”)。我想在一个div中显示唯一值,并使用相同列表在同一页面中的另一个div中显示所有值信息
请注意:我在这里解释了简单的场景。所以你可能认为在python中使用 set 方法来防止重复值。在我的情况下不可能,我必须将一个对象发送到django模板
在一个页面中有两个div,它应显示来自同一对象的不同信息。
DIV 1:
{% for v in Info %}
{{v}} // Show unique values ("hi","hello","hej","hey")
{% endfor %}
DIV 2:
{% for v in Info %}
{{v}} // Show all the values ("hi","hello","hi","hello","hej","hey")
{% endfor %}
请告诉我您的意见
答案 0 :(得分:1)
使用自定义过滤器:
@register.filter(name='unique')
def unique(value, arg):
# put your complex unique logic here
return set(value)
参考https://docs.djangoproject.com/en/1.8/howto/custom-template-tags/#writing-custom-template-filters
将其用作{% for v in Info|unique %} {{v}} {%endfor%}
请注意,调用集会搞乱列表的顺序