Search code examples
pythonhtmlpugpyjade

Loop with counter


I'm trying to do the age-old gallery loop counter using jade (I'm a newb). I'm using twitter bootstrap so I need to put the images into divs with col-md-3 as a class and as a child of a div with row". So, ideally it looks like this:

<div class="row">
    <div class="col-md-3">image goes here</div>
    <div class="col-md-3">image goes here</div>
    <div class="col-md-3">image goes here</div>
    <div class="col-md-3">image goes here</div>
</div>
<div class="row">
    <div class="col-md-3">image goes here</div>
    <div class="col-md-3">image goes here</div>
    <div class="col-md-3">image goes here</div>
    <div class="col-md-3">image goes here</div>
</div>

Where I'm stuck is how to initialize a new row since indentation matters in jade. Below is what I'm starting with, how do I proceed?

div.row
    each product, index in collection.products
        div.col-md-3: img

I would assume you'd use something like:

if index % 3
    div.row

...but it doesn't feel quite right...


Solution

  • Solved it going a different direction. I created a context_processor at the top of my views.py file and that made it available to my template as a function.

    views.py

    @app.context_processor
    def utility_processor():
        def subdivide_list(list_to_group, group_size):
            return [list_to_group[i:i+group_size] for i  in range(0, len(list_to_group), group_size)]
    return dict(subdivide_list=subdivide_list)
    

    gallery.jade

    div.col-md-9
        for product_row in subdivide_list(all_products, 4)
            div.row
                for product in product_row
                    img(src="{{ url_for('static', filename='uploads/images/products/'+product.image.name_thumb) }}")