小胡子条件和循环 [英] Mustache Conditions and Loops

查看:121
本文介绍了小胡子条件和循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是资源:

JSON

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

算法

{{ 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 }}

如何编写此算法以使用Mustache编译器?

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

我需要这样做才能与双方合作,第一个是RubyOnRails应用程序,第二个是客户端(JavaScript)。

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

推荐答案

您的问题有两种解决方案。

There are two solutions to your problem.

以下是胡须文档中的示例:

Here is an example from the mustache documentation:

{
  "repos": []
}

模板:

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

输出:

No repos :(

As你看到反转的选择让我做条件逻辑。在你的情况下,它看起来像:

As you see the inverted selections let me do conditional logic. In your case it would look something like:

Json:

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

小胡子:

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



不要在无逻辑模板中做逻辑



这就是我要做的。如果你的Mustache模板中有条件逻辑,我认为你做错了。您可以使用 Handlebars ,而这在这方面要先进得多,或者将您的逻辑移到其他地方(到您的javascript)。

Don't do logic in logic-less templating

This is what I would do. If you have conditional logic in your Mustache templates I think you're doing it wrong. You can either use Handlebars instead which is much more advanced in this regard or move your logic someplace else (to your javascript).

请参阅 Moustache自述文件

这篇关于小胡子条件和循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆