简体   繁体   中英

How to unpack more than one variable on Jinja2

I'm trying to unpack more than one variable on jinja template engine. How can I achieve this?

I'm trying to achieve something like this;

{% for item1, item2, item3 in items %}
<div class="row">
  <div class="four columns">
    <img src="static{{ item1.pics.0 }}" class="picitem" alt=""/>
  </div>

  <div class="four columns">
    <img src="static{{ item2.pics.0 }}" class="picitem" alt="" />
  </div>

  <div class="four columns">
    <img src="static{{ item3.pics.0 }}" class="picitem" alt=""/>      
  </div>
</div>
{% endfor %}

This is obviously not working by giving;

ValueError: too many values to unpack

Any ideas would be appreciated.

Use the batch filter to iterate over chunks:

{% for tmp in items|batch(3) %}
  <div class="row">
    {% for item in tmp %}
      <div class="four columns">
        <img src="static{{ item.pics.0 }}" class="picitem" alt=""/>
      </div>
    {% endfor %}
  </div>
{% endfor %}

You have to reconstruct your 'items' to make unpacking work.

for example:

item1 = [1,2,3]
item2 = [a,b,c]
item3 = [11,22,33]

items = zip(item1, item2, item3)

Send this to template. Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM