How can I render object containing dictionaries to templates in jinja2?

suppose If lists are a1=[ ],a2=[ ],a3=[ ],a4=[ ],a5=[ ]

they all will have dynamic values as below:

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

I want to render only those which has values as in this case a3 and a5 then how can I check lists which have values then render it to template 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>

and create a link to get specific object table, how can I do that?

<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>

1 answer

  • answered 2018-02-13 03:03 Rakesh

    You can combine all the list and then iterate over it.

    Example:

    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)
    

    Output:

    <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>