Search code examples
pythonpython-3.xloopsflasksemantic-ui

How to fill 2 column cards from Python loop


enter image description hereIm trying to loop over a Python list to fill out rows of 2 centered Semantic UI cards but not getting how to correctly fill the second card in the row. At the moment I have in my code the string "hey" but before that I had the 'user' but of course was getting the same user twice : /

     [![enter image description here][1]][1]<div class="ui two column centered grid">
        {% for user in users %}
          <div class="four column centered row">
            <!-- card 1 -->
            <div class="column"><div class="ui card">
              <div class="image">
                <img src="/static/images/matthew.png">
              </div>
              <div class="content">
                <a class="header" href="{{ url_for('show', id=user.id)}}">{{ user.first_name }}</a>
                <div class="meta">
                  <span class="date">Joined in 2013</span>
                </div>
                <div class="description">
                  {{ user.first_name }} is a surfer living in Aguadilla.
                </div>
              </div>
              <div class="extra content">
                <a>
                  <i class="user icon"></i>
                  22 Friends
                </a>
              </div>
            </div></div>
            <!-- card 2 -->
            <div class="column">hey</div>
          </div>
        {% endfor %}
      </div>

Solution

  • If you have flat list [0, 1, 2, 3, ...] instead of [ [0,1], [2,3], ...] then you can try to use slicing with zip() to convert it.

    Using users[0::2] you can get even users (0,2,4, ...),

    Using users[1::2] you can get odd users (1,3,5, ...)

    And using it with zip() you can create pairs (0,1), (2,3), ... which you can use to create rows with two cards.

    for user1, user2 in zip(users[0::2], users[1::2]):
        # ... create card1 with user1 ...
        # ... create card2 with user2 ...
    

    I don't know if zip() can be used in template but eventually you can use this method to create list [ [0,1], [2,3], ...] before sending it to template.