neil manuell
neil manuell

Reputation: 225

chunking an array in jade template

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]])

Upvotes: 3

Views: 1519

Answers (2)

Reinier Garcia
Reinier Garcia

Reputation: 1700

I just did something similar.

SOLUTION:

Step # 1: Add the necessary instance method to the Array class prototype:

Place this in the controller that calls/renders the view where you will be calling that mixin.

Array.prototype.each_slice = function (size, callback) {
    for (let i = 0, l = this.length; i < l; i += size) {
        callback.call(this, this.slice(i, i + size));
    }
};

Step # 2: Render properly the array slices in your pug file.

if myArray && myArray.length > 0
    - myArray.each_slice(2, (slice) => {
    +carouselItem(...slice)
    - })

For example, I just did this using Node.js + Express + Pug(ex Jade)

This is the home controller: controllers/home.controller.js

const {CodingSkill} = require('../models');
const {errorsHelper} = require('./../utilities');

Array.prototype.each_slice = function (size, callback) {
    for (let i = 0, l = this.length; i < l; i += size) {
        callback.call(this, this.slice(i, i + size));
    }
};

exports.index = async (request, response, next) => {

    try {
        const codingSkills = await CodingSkill.find({}).sort({percentage: -1});
        response.render('home/index', {pageTitle: 'Any title', codingSkills})
    } catch (error) {
        request.toastr.error(error, 'Server Error!');
        errorsHelper.status500(error, next);
    }

}

This is the home index view that includes the partial: views/home/index.pug

enter image description here

And finally this is the partial: views/home/includes/skills_dynamic.pug

section#skills.skills.section-bg
    .container
        .section-title
            h2 Skills
            p
                | Magnam dolores commodi suscipi. Necessitatibus eius consequatur ex aliquid fuga eum quidem. Sit sint consectetur velit. Quisquam quos quisquam cupiditate. Et nemo qui impedit suscipit alias ea. Quia fugiat sit in iste officiis commodi quidem hic quas.
        if codingSkills && codingSkills.length > 0
            - codingSkills.each_slice(2, (slice) => {
            .row.skills-content
                .col-lg-6(data-aos='fade-up')
                    .progress
                        span.skill
                            | #{slice[0].name}
                            i.val #{slice[0].percentage}%
                        .progress-bar-wrap
                            .progress-bar(role='progressbar', aria-valuenow=slice[0].percentage, aria-valuemin='0', aria-valuemax='100')
                if (slice[1])
                    .col-lg-6(data-aos='fade-up', data-aos-delay='100')
                        .progress
                            span.skill
                                | #{slice[1].name}
                                i.val #{slice[1].percentage}%
                            .progress-bar-wrap
                                .progress-bar(role='progressbar', aria-valuenow=slice[1].percentage, aria-valuemin='0', aria-valuemax='100')


            - })

Visual Result:

enter image description here

Upvotes: 0

Tom
Tom

Reputation: 26829

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.

Upvotes: 1

Related Questions