Django 模板渲染嵌套的生成器表达式的问题

2019-01-17 12:01:36 +08:00
 chenstack

views 部分复现代码

from django.http import HttpResponse
from django.template import Context
from django.template import Template


def test(request):
    src = [
        {"a": 1, "b": 2},
        {"a": 10, "b": 20},
    ]

    fields = ["a", "b"]
    data = ((item[field] for field in fields) for item in src)

    # for item in data:
    #     print(list(item))  # 这样是正常的

    template = Template('''
        {% for item in data %}
            {% for value in item %} {{ value }} {% endfor %}
        {% endfor %}
    ''')
    context = Context({'data': data})
    html = template.render(context)

    print(html)
    return HttpResponse()

模板里面内层生成器取到的 item 似乎是外层循环的最后一项,渲染结果都是 10 20。把内层生成器表达式改成列表推导式就正常了。很好奇这个问题的原因。

1619 次点击
所在节点    Python
2 条回复
chenstack
2019-01-17 12:08:26 +08:00
测试的环境是 Python 3.7.2 和 Django 2.1.5
punderson
2019-01-17 13:05:42 +08:00

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/527883

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX