Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

chunking an array in jade template

Tags:

templates

pug

I have an array, and a mixin that takes an array as a param. How would I chunk the array into sections of four and pass to the mixin?

So something sort of like this but better and working:

 each index, i in myArray
     if i%4 == 0
         +carouselItem([myArray[i], myArray[i+1], myArray[i+2], myArray[i+3]])
like image 728
neil manuell Avatar asked Apr 24 '26 23:04

neil manuell


1 Answers

I would suggest a bit different approach: convert your array into two-dimensional array in your request handler function and then perform iteration over two-dimensional array (array of arrays) in your Jade template.

With that approach the template will be much simpler and all conversion will happen inside the handler method (controller) where you can have access to different libraries etc.

Example: In order to convert an array into two-dimensional array you could use following method:

function arrayTo2DArray (list, howMany) {
    var result = []; input = list.slice(0); 
    while(a[0]) { 
        result.push(a.splice(0, howMany)); 
    }
    return result;
}

And your request handler could look as follows:

exports.handler = function(req, res) {

    // myArray with some values

    res.render('template' { 
        myArray: arrayTo2DArray(myArray, 4) 
    }
}

If your myArray was, say, ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'], arrayTo2DArray(myArray, 4) would return

[
    ['a', 'b', 'c', 'd'], 
    ['e', 'f', 'g', 'h']
]

Your Jade template could look like this (much simpler)

each values in myArray
    +carouselItem(values)

I hope that will help.

like image 84
Tom Avatar answered Apr 27 '26 20:04

Tom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!