简体   繁体   English

mustache.js模板引擎中的表示逻辑

[英]Presentation logic inside mustache.js template engine

What is the simplest way to achieve the following presentation with client-side mustache.js template engine ? 使用客户端mustache.js模板引擎实现以下演示的最简单方法是什么?

var view = {
  search_term: 'something',
  number_of_hits: 3,
  hits: [...]
};

If number_of_hits == 0 then print on screen: "No results found" 如果number_of_hits == 0,则在屏幕上打印:“未找到结果”

If number_of_hits == 1 then print on screen: "One result found" 如果number_of_hits == 1,则在屏幕上打印:“找到一个结果”

If number_of_hits > 1 then print on screen: " N results found" 如果number_of_hits > 1,则在屏幕上打印:“找到N个结果”

Knowing that mustache is logic-less template engine, is it at all possible to do it with the existing mustache tags or I will have to change the JSON respond? 知道胡须是无逻辑的模板引擎,是否可以使用现有的胡须标签完全做到这一点,否则我将不得不更改JSON响应?

With Mustache it's possible to differentiate between the value 0 and non- 0 values using the {{#section}} and {{^inverted}} tags: 使用Mustache,可以使用{{#section}}{{^inverted}}标签区分0和非0值:

<!-- If number_of_hits is not 0, show hits -->
{{#number_of_hits}}
 {{number_of_hits}} hits
{{/number_of_hits}}

<!-- If number of hits is 0 (or any other falsy value) -->
{{^number_of_hits}}
  No hits
{{/number_of_hits}}

As far as I know, Mustache cannot detect the difference between 1 and 2, for instance. 据我所知,Mustache无法检测到1和2之间的差异。 For that you'll have to modify the view object you pass into the template. 为此,您必须修改传递到模板中的view对象。 Possibly something like: 可能是这样的:

var hits = 3;
var view = {
  search_term: 'something',
  number_of_hits: hits,
  hitkind: { 
    none: hits === 0,
    one:  hits === 1,
    many: hits > 1
  }
};

And in the template 并在模板中

{{#hitkind.none}} No hits {{/hitkind.none}}
{{#hitkind.one }} One hit {{/hitkind.one}}
{{#hitkind.many}} {{number_of_hits}} hits {{/hitkind.many}}

Alternatively you could consider changing your templating engine to Handlebars.js . 或者,您可以考虑将模板引擎更改为Handlebars.js Handlebars is a superset of Mustache, which means that all your Mustache templates will work with it. 车把是Mustache的超集,这意味着您的所有Mustache模板都可以使用。 Handlebars templates are logicless just like Mustache's, so it doesn't enable you to write the logic directly to the template. 就像Moustache的那样,车把模板是无逻辑的,因此它不能使您直接将逻辑写入模板。 Instead it provides a concept of Helpers , or functions callable from your templates. 相反,它提供了Helpers的概念,或可从模板调用的函数。

With Handlebars you can define a helper, like: 使用把手,您可以定义一个助手,例如:

Handlebars.registerHelper('hitCount', function(count) {
  if(count === 0) return "No hits";
  if(count === 1) return "One hit";
  return count + " hits".
});

And call it from a template: 并从模板调用它:

{{hitCount number_of_hits}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM