且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

小胡子条件和循环

更新时间:2023-12-01 08:16:40

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

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自述文件