【问题标题】:How can I render object containing dictionaries to templates in jinja2?如何将包含字典的对象渲染到 jinja2 中的模板?
【发布时间】:2018-02-13 03:03:53
【问题描述】:

假设如果列表是a1=[ ],a2=[ ],a3=[ ],a4=[ ],a5=[ ]

它们都将具有如下动态值:

a1=[]
a2=[]
a3=[{'car':'bez','city':'la','aero':'vaar'}]
a4=[]
a5=[{'car':'tez','city':'pa','aero':'vawear'}]

我只想渲染具有值的那些,在这种情况下是 a3 和 a5,那么我如何检查具有值的列表,然后将其渲染到模板 card.html

<table>
<tbody>
<thead>
<th>car</th>
<th>city</th>
<th>aero</th>
</thead>
{{for key in a3 /a5}}
<td>key[car]</td>
<td>key[city]</td>
<td>key[aero]</td>
</tbody>
</table>

并创建一个链接来获取特定的对象表,我该怎么做?

<html>
<body>
<p><a hr ef="/card">card</a></p> """which gives a3 value"""
<p><a href="/card">card</a></p>"""which gives a5 value"""
</body>
</html>

【问题讨论】:

  • 在第一行中,您的字典实际上是列表。后来a3a5无效。
  • 修改没有改进。
  • 都是列表(不是字典),其中两个只有字典。

标签: python html python-3.x templates jinja2


【解决方案1】:

您可以组合所有列表,然后对其进行迭代。

示例:

from jinja2 import Template

myString = """<table>
    <tbody>
        <thead>
            <th>car</th>
            <th>city</th>
            <th>aero</th>
        </thead>
        {% for key in data %}
            <td>{{ key['car'] }}</td>
            <td>{{ key['city'] }}</td>
            <td>{{ key['aero'] }}</td>
        {% endfor %}
    </tbody>
</table>"""

a1=[]
a2=[]
a3=[{'car':'bez','city':'la','aero':'vaar'}]
a4=[]
a5=[{'car':'tez','city':'pa','aero':'vawear'}]

d = (a1 + a2 + a3 + a4 + a5)
data = Template(myString).render({'data': d})
print(data)

输出:

<table>
    <tbody>
        <thead>
            <th>car</th>
            <th>city</th>
            <th>aero</th>
        </thead>

            <td>bez</td>
            <td>la</td>
            <td>vaar</td>

            <td>tez</td>
            <td>pa</td>
            <td>vawear</td>

    </tbody>
</table>

【讨论】:

    猜你喜欢
    • 2015-01-06
    • 2013-10-09
    • 2018-08-19
    • 2011-01-12
    • 2011-05-16
    • 1970-01-01
    • 2017-03-01
    • 1970-01-01
    相关资源
    最近更新 更多