推荐学习书目
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 · Jan 17, 2019 · 2670 views
    This topic created in 2695 days ago, the information mentioned may be changed or developed.

    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 replies    2019-01-17 13:05:42 +08:00
    chenstack
        1
    chenstack  
    OP
       Jan 17, 2019
    测试的环境是 Python 3.7.2 和 Django 2.1.5
    punderson
        2
    punderson  
       Jan 17, 2019   ❤️ 1
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3311 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 11:53 · PVG 19:53 · LAX 04:53 · JFK 07:53
    ♥ Do have faith in what you're doing.