val_ya
val_ya

Reputation: 99

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?

Upvotes: 0

Views: 1001

Answers (2)

Peter Seliger
Peter Seliger

Reputation: 13376

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

Upvotes: 1

Gibin Ealias
Gibin Ealias

Reputation: 2859

I see multiple issues with your code. Your mixin definition is techs but you are trying to call tech. Secondly the indentation is incorrect after the mixin declaration. Also, the array should be passed as an object with an identifier.

Therefore, consider restructuring your JSON onto,

{
  "tempArrayName": [
    {
      "title": "Title1",
      "broadcast": true
    },
    {
      "title": "Title2",
      "broadcast": false
    }
  ]
}

And your JADE/PUG could be rewritten as,

mixin techs
 - var data = tempArrayName;
 ul.techs
    each item in data
        if item.broadcast
            li
              .h2= item.title
+techs

Where +techs is the mixin call which can be reused in multiple places. It checks for the condition usin broadcast value (hope that is what you are trying to achieve) and prints,

<ul class="techs">
  <li>
    <div class="h2">Title1</div>
  </li>
</ul>

Tested using - http://naltatis.github.io/jade-syntax-docs

Hope this helps.

Upvotes: 0

Related Questions