Vivian  Tio Vivian Tio -3 years ago 126
Python Question

How to zip 2 different length array so that can loop in django loop?

I have 2 arrays:

First array:

['Tan','Goh','Tio']

Second array:

[['Honda','Toyota','Proton'],['Toyota'],['Proton','Lambo']]

How to zip this 2 arrays so that when i apply this code:

{% for i in loop_times %}

{{i|safe}}

{% endfor %}


So,the out put will be like this:

<li>
<a href="#">
<span class="ca-icon">Tan</span>
<div class="ca-content">
<h3 class="ca-main">Honda</h2>
<h3 class="ca-sub">Toyota</h3>
<h3 class="ca-sub">Proton</h3>
</div>
</a>
</li>

<li>
<a href="#">
<span class="ca-icon">Goh</span>
<div class="ca-content">
<h3 class="ca-sub">Toyota</h3>
</div>
</a>
</li>
<li>
<a href="#">
<span class="ca-icon">Tio</span>
<div class="ca-content">
<h3 class="ca-main">Proton</h2>
<h3 class="ca-sub">Lambo</h3>
</div>
</a>
</li>


Anyone can share me idea? I have study this https://docs.djangoproject.com/en/1.11/ref/templates/builtins/ but I still not able to understand, can anyone give some ideas ?

Answer Source

in views.

l = ['Tan', 'Goh', 'Tio']
d = [['Honda', 'Toyota', 'Proton'], ['Toyota'], ['Proton', 'Lambo']]
list = dict(zip(l, d))

in the template:

{% for key, values in list.items %}
    <a href="#">
    <span class="ca-icon">{{ key }}</span>
    <div class="ca-content">
        {% for v in values %}
        <h3 class="ca-main">{{ v }}</h2>
        {% endfor %}
    </div>
    </a>
{% endfor %}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download