Mustache and loop conditions

Here are the resources:

Json

{
  "badges":{
    "unlocked": [
      {"name": "Win 1"},
      {"name": "Win 2"},
      {"name": "Win 3"}
    ],
    "locked":[
      {"name": "Lose 1"},
      {"name": "Lose 2"},
      {"name": "Lose 3"}
    ]
  }
}

Algorithm

{{ if_has_badges }}
<div class="badges">
  <h1>Badges</h1>

  {{ if_has_badges_unlocked }}
    <div class="badges-unlocked">
      <h2>Unlocked!</h2>
      {{ loop_badges_unlocked }}
      <a href="#" class="badge">
        <strong>{{ name }}</strong>
      </a>
      {{ end_loop_badges_unlocked }}
    </div>
  {{ end_if_has_badges_unlocked }}

  {{ if_has_badges_locked }}
    <div class="badges-locked">
      <h2>Locked!</h2>
      {{ loop_badges_locked }}
      <a href="#" class="badge">
        <strong>{{ name }}</strong>
      </a>
      {{ end_loop_badges_locked }}
    </div>
  {{ end_if_has_badges_locked }}

</div>
{{ end_if_has_badges }}

How can I write this algorithm to work with the Mustache compiler?

I need to do this to work with two parties, first this is a RubyOnRails application, and the second is client-side (JavaScript).

+5
source share
2 answers

There are two solutions to your problem.

Using selections and inverted selections

Here is an example from the mustache documentation:

{
  "repos": []
}

Template:

{{#repos}}<b>{{name}}</b>{{/repos}}
{{^repos}}No repos :({{/repos}}

Conclusion:

No repos :(

As you can see, inverted selections allow me to do conditional logic. In your case, it will look something like this:

Json:

var viewModel = {
    badges:[]//badges here
}
viewModel.anyBadges = badges.length >0;

Mustache:

    <div class="badges-unlocked">
   {{#anyBadges}}
      <h2>Unlocked!</h2>
   {{/anyBadges}}
   {{#badges_unlocked}}
      <a href="#" class="badge">
        <strong>{{ name }}</strong>
      </a>
   {{/badges_unlocked}}

Do not follow logic without patterns

, . Mustache, , . Handlebars, - ( javascript).

, Mustache readme

+7

( Ruby, JavaScript) , ( if_has_badges) View.

, Ruby JavaScript, length:

{{# badges.length }}
<div class="badges">
  <h1>Badges</h1>

  {{# badges.unlocked.length }}
    <div class="badges-unlocked">
      <h2>Unlocked!</h2>
      {{# badges.unlocked }}
      <a href="#" class="badge">
        <strong>{{ name }}</strong>
      </a>
      {{/ badges.unlocked }}
    </div>
  {{/ badges.unlocked.length }}

  {{# badges.locked.length }}
    <div class="badges-locked">
      <h2>Locked!</h2>
      {{# badges.locked }}
      <a href="#" class="badge">
        <strong>{{ name }}</strong>
      </a>
      {{/ badges.locked }}
    </div>
  {{# badges.locked.length }}

</div>
{{/ badges.length }}

...

+5

All Articles