Search code examples
javascriptpug

pug for loop - trying to dynamically create # of li items via a number passed in by mixin argument


I'm trying to dynamically create a number of lis equals to the number passed in by a mixin. I tried using for loops, but nothing is being generated.

Here is what the mixin looks like:

mixin grid-content(liCount,itemTitle1, itemDescriptionTitle1, itemDescription1, itemTitle2, itemDescriptionTitle2, itemDescription2, itemTitle3, itemDescriptionTitle3, itemDescription3)
    - var count = liCount
    .grid-content
        .container
            .row
                ul.grid-content__list.grid-content__list--not-news
                    each val in count
                        li.grid-content__item
                            h1.item-title=itemTitle+count
                            .item-content
                                h3.item-description-title=itemDescriptionTitle+count
                                p.item-description=itemDescription+count

Solution

  • There are many things going on here. First, consider the following:

    Say count = 3. One might think p= itemTitle+count is equivalent to p= itemTitle3, but it's not. Instead, it looks for a variable called itemTitle and tries to sum its value with a variable called count, which doesn't seem to be what you're trying to do.

    If you're trying to create a mixin that can easily accept any number of grid items, consider passing an array of objects.

    You might consider an approach like this:

    // My Grid items
    
    -
      var myGridItems = [
        {
          title: 'Item One Title',
          description: {
            title: 'Item One Description Title',
            contents: 'Item One Description Contents'
          }
        },
        {
          title: 'Item Two Title',
          description: {
            title: 'Item Two Description Title',
            contents: 'Item Two Description Contents'
          }
        },
        {
          title: 'Item Three Title',
          description: {
            title: 'Item Three Description Title',
            contents: 'Item Three Description Contents'
          }
        }
      ]
    
    
    // My Mixin
    
    mixin gridContent(items)
    
      .grid-content
        .container
          .row
            ul.grid-content__list.grid-content__list--not-news
    
              each item in items
    
                li.grid-content__item
                  h1.item-title= item.title
                  .item-content
                    h3.item-description-title= item.description.title
                     p.item-description= item.description.contents
    
    
    // Calling the Mixin
    
    +gridContent(myGridItems)