假设一个list0
包含元素['a','b','c','d']
,我需要根据模板变量^{
到目前为止,我找到的更好的方法是创建一个自定义标记,如here或here和django doc中所述。
定义后,您可以编写如下内容:
{% for elm in list0 %}
{{ elm }} {{ list1|index:forloop.counter0 }}
{% endfor %}
该示例假定有另一个列表list1
,其中包含元素['A','B','C','D']
。index
是自定义筛选器的名称,它使用forloop计数器作为索引来获取每个list1
元素:list1[0]
,list1[1]
,list1[2]
,list1[3]
这就产生了:
a A
b B
c C
d D
但是如果您只想使用内置过滤器呢?
(或者有空余时间做娱乐活动?
经过一些研究和测试,我发现的唯一方法是这样一件奇怪的事情:
{% for elm in list0 %}
{% with sl0=forloop.counter0|make_list sl1=forloop.counter|make_list %}
{% with header_id=sl0.0|add:":"|add:sl1.0 %}
{{ elm }} {{ list1|slice:header_id|join:"" }}
{% endwith %}
{% endwith %}
{% endfor %}
它的作用是:
It uses the slice builtin filter. slice needs a string representing a python list part like
'[2:3]'
which is generated by the secondwith
and the twoadd
. So one need to slice one member at a time using the forloop counters :'[0:1]'
,'[1:2]'
,'[2:3]'
...Butforloop.counter0
andforloop.counter
are integers, andadd
does not generate a string in this case. It tries to get an integer as a result. So it needs to be converted to a string. This is whymake_list
is used in the firstwith
, as it's the only way I found so far to change an integer into a string..finally slice returns a list with one element so it uses ajoin:""
to convert it to a string.
我希望我在文档中遗漏了一些东西,因为上面的代码是。。好很可怕,但很有趣
如何使用django模板内置项以有效的方式满足这一需求?
我同意在视图中而不是在模板中构建上下文时应该处理它,但假设它无法完成
您不应该在模板中执行此操作,模板用于渲染逻辑,它取决于视图以提供正确的结构。我们可以用^{} 实现这一点:
然后使用以下命令渲染此内容:
相关问题 更多 >
编程相关推荐