V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
chenstack
V2EX  ›  Python

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

  •  
  •   chenstack · 2019-01-17 12:01:36 +08:00 · 1583 次点击
    这是一个创建于 1898 天前的主题,其中的信息可能已经有所发展或是发生改变。

    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。把内层生成器表达式改成列表推导式就正常了。很好奇这个问题的原因。

    2 条回复    2019-01-17 13:05:42 +08:00
    chenstack
        1
    chenstack  
    OP
       2019-01-17 12:08:26 +08:00
    测试的环境是 Python 3.7.2 和 Django 2.1.5
    punderson
        2
    punderson  
       2019-01-17 13:05:42 +08:00   ❤️ 1
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5825 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 06:14 · PVG 14:14 · LAX 23:14 · JFK 02:14
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.