【问题标题】:Django template - For loop through two values each timeDjango 模板 - For 每次循环两个值
【发布时间】:2014-07-12 02:17:40
【问题描述】:

我正在使用视图和模板。

我的视图中有这个列表

[u'kevinelamo', 50, u'kevin', 4200, u'andres', 200, u'user342', 0, u'cateto', 0]

然后我将它发送到模板..

在模板中自动解析如下:

[{"username": "kevinelamo", "time": 50}, {"username": "kevin", "time": 4200}...] 

我想这样迭代:

{% for username,time in llistat_usuaris %}
<h1>My name is <h1>{{username}}
{{time}}
{% endfor %}

但这给了我列表中的一个字符

My name is
[
My name is
{
My name is
"
My name is
u
My name is
s
My name is
e
My name is
r
My name is
n
My name is
a
My name is
m
My name is
e
My name is

我该如何处理?谢谢

【问题讨论】:

  • 您需要展示您的视图如何将数据发送到模板,以及模板中“自动解析”的含义。从您的输出来看,您似乎将其作为字符串发送。
  • 我的意思是自动解析,当我将它传递给模板时,格式会发生变化,正如您在我的问题中看到的那样。

标签: django templates django-templates


【解决方案1】:

如果你有这个列表:

l = [u'kevinelamo', 50, u'kevin', 4200, u'andres', 200, u'user342', 0, u'cateto', 0]

你可以把它转换成字典:

l_dict = dict(zip(l[::2], l[1::2]))

这将使l_dict:

{u'andres': 200, u'cateto': 0, u'user342': 0, u'kevin': 4200, u'kevinelamo': 50}

然后遍历模板中的键值对:

{% for username, time in l_dict.items %}
    <h1>My name is <h1>{{ username }}
    {{ time }}
{% endfor %}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-26
    • 2013-10-26
    • 2021-10-17
    • 2020-10-14
    相关资源
    最近更新 更多