【问题标题】:Dynamically populate template from two lists从两个列表中动态填充模板
【发布时间】:2013-07-27 15:58:29
【问题描述】:

我想从两个包含变量值的列表中动态填充模板。

谁能告诉我,我怎么能做到这样:

current_task_resources_types = ["image", "html"]
current_task_resources_names = ["elephant.png", "index.html"]

"task": [
    {% for index in current_task_resources.length %}
        {"type": "{{ current_task_resources_types.index }}", "url": "{{ current_task_resources_names.index }}"},
    {% endfor %}
],

【问题讨论】:

    标签: django django-templates python-2.x


    【解决方案1】:

    您可以zip您视图中的列表,

    current_task_resources = zip(current_task_resources_types, current_task_resources_names)
    

    然后遍历模板中的压缩列表

    "task": [
        {% for type, name in current_task_resources %}
            {"type": "{{ type }}", "url": "{{ names }}"},
        {% endfor %}
    ]
    

    在 Python 2 中,如果列表很长,itertools.izip 可能会提高性能。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-05
      • 1970-01-01
      相关资源
      最近更新 更多