Django模板使用模板变量作为索引获取列表项

2024-09-30 04:30:56 发布

您现在位置:Python中文网/ 问答频道 /正文

假设一个list0包含元素['a','b','c','d'],我需要根据模板变量^{}或模板中可用的任何其他整数获取第n个元素

到目前为止,我找到的更好的方法是创建一个自定义标记,如hereheredjango 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 second with and the two add. So one need to slice one member at a time using the forloop counters : '[0:1]', '[1:2]', '[2:3]'...But forloop.counter0 and forloop.counter are integers, and add 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 why make_list is used in the first with, 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 a join:"" to convert it to a string.

我希望我在文档中遗漏了一些东西,因为上面的代码是。。好很可怕,但很有趣

如何使用django模板内置项以有效的方式满足这一需求?
我同意在视图中而不是在模板中构建上下文时应该处理它,但假设它无法完成


Tags: thetoinadd模板元素stringwith
1条回答
网友
1楼 · 发布于 2024-09-30 04:30:56

您不应该在模板中执行此操作,模板用于渲染逻辑,它取决于视图以提供正确的结构。我们可以用^{}实现这一点:

from django.shortcuts import render

def my_view(request):
    list0 = ['a', 'b', 'c', 'd']
    list1 = ['A', 'B', 'C', 'D']
    list01 = zip(list0, list1)
    return render(request, 'some_template.html', {'list01': list01})

然后使用以下命令渲染此内容:

{% for elm0, elm1 in list01 %}

{{ elm0 }} {{ elm1 }}

{% endfor %}

相关问题 更多 >

    热门问题