Search code examples
pugmixins

Pug (Jade) mixin and if statement


Well, I have objects in array named data:

[
 {
  title: 'Title',
  broadcast: true
 },
 {
  title: 'Title',
  broadcast: false
 }
]

On one page I want to show only ones with broadcast: true and I want to use a mixin call for that. My mixin:

mixin techs(condition)
- var data = trs.tech.data;
ul.techs
    each item in data
        if condition
            li
              .h2= item.title

And my mixin call:

+techs('item.broadcast')

But (of course) this thing doesn't work as I want to. It shows all objects in array. Is there any way to get result I expect without writing condition into mixin?


Solution

  • From my point of view, regarding this given problem, the mixin should not at all contain any additional logic connected to the data it receives. It instead should be a straightforward render method that iterates a list. Thus, in this case, the render method exclusively processes a list of already filtered/sanitized/proven data items, passed as this method's sole argument.

    // running, js only, demo code
    
    var techList = [{
      title: 'Title',
      broadcast: true
    }, {
      title: 'Title',
      broadcast: false
    }];
    
    
    function isMarkedForBroadcast(type/*, idx, list*/) {
      return (type.broadcast === true);
    }
    
    
    var broadcastItemList = techList.filter(isMarkedForBroadcast);
    
    console.log('techList : ', techList);
    console.log('broadcastItemList : ', broadcastItemList);
    .as-console-wrapper { max-height: 100%!important; top: 0; }
    //- pug/view
    
    mixin renderTechList(list)
        ul.techs
            each item in list
                li
                    .h2= item.title
    
    -
        function isMarkedForBroadcast(type/*, idx, list*/) {
            return (type.broadcast === true);
        }
    
    +renderTechList(trs.tech.data.filter(isMarkedForBroadcast))