Search code examples
variablespug

How to call a different variable from a single jade mixin?


I have 6 cards to display in one side a title and a list. As they all have the same structure, I am creating a mixin using Jade. So as each card displays a different list, I need to create different variables, one for each list. Is it possible, and if so, how to create a changeable argument that when I use this mixin, I can change only the last argument to access the variable that I need? like:

I'll have my 6 different variables with the list items

-var benefitsCard1 = ['benefit 1', 'benefit 2', 'benefit 3, 'benefit 4'];
-var benefitsCard2 = ['benefit 5', 'benefit 6', 'benefit 7, 'benefit 8'];

...

and in the mixin, where it says benefitsCard1 (last argument) I would like to change to the name of the variable I need to access to create the list, or maybe, if possible, to create a mixin with an empty arg (like ' ' ) in order to name this arg the variable I want to access. Is this possible?

mixin benefits(image, h4, p4, benefitsCard1)
  .col-sm-4
    .benefits__card-front
      img(src='img/' + image + '.svg')
      h4
        | #{strings[''+h4]}
      p4
        | #{strings[''+p4]}
    .benefits__card-back
      h4
        | #{strings[''+h4]}
      ul
        each benefit in benefitsCard1
          li
            p1
             | #{strings[''+benefit]}

Solution

  • Parameters in Pug mixins work just like they do in JavaScript functions—if you pass a variable as an argument, you can access the value of that variable using the parameter's name, instead of the name of the original variable.

    As such, you could just name the parameter in your mixin benefits, and access it that way.

    Mixin Declaration

    mixin benefitsList(benefits)
      ul
        each benefit in benefits
          li #{benefit}
    

    Usage

    - var benefits1 = ['one', 'two', 'three']
    - var benefits2 = ['four', 'five', 'six']
    - var foobar = ['seven', 'eight', 'nine']
    
    +benfitsList(benefits1)
    +benfitsList(benefits2)
    +benfitsList(foobar)
    +benfitsList(['ten', 'eleven', 'twelve'])
    

    Output

    <ul>
      <li>one</li>
      <li>two</li>
      <li>three</li>
    </ul>
    <ul>
      <li>four</li>
      <li>five</li>
      <li>six</li>
    </ul>
    <ul>
      <li>seven</li>
      <li>eight</li>
      <li>nine</li>
    </ul>
    <ul>
      <li>ten</li>
      <li>eleven</li>
      <li>twelve</li>
    </ul>
    

    Hope this helps.