Switch case in MustacheJs

孤街醉人 提交于 2019-12-12 01:32:51

问题


Using Mustache js (a logic less templating) is there a way i can achieve switch case? this i need because a class is assigned to dom element based on the value for example:

switch(tasks.Count)
{
   case 0:
       element.Class = "no-tasks";
    break;
   case 1:
       element.Class = "one-tasks";
   break;
.
.
.
}

that's the code i got now, how do i transform it to template( I Believe having methods on model being rendered is the one option) But adding methods to determine which class to use is an overkill and besides that is going to pollute my model to a swamp!!

  • I ask this because i am using Nustache a port of MustacheJs to C#, .NET to render nested model.Anything that applies to Mustache also applies to Nustache

回答1:


There's a few ways to do this.

In Javascript, if Mustache encounters a function in a value, it will call it using the enclosed text as the only argument.

var data = {
    foo: function(text) { return '<b>' + text + '</b>'; }
}

mustache

{{#foo}}
   HI I LIKE FISH, thanks.
{{/foo}}

outputs

<b>HI I LIKE FISH, thanks.</b>

Search for "lambda" in the mustache docs.

Another way to do it is do a falsey/truthy check.

data

{ foo: true }

mustache

{{#foo}}
  output this if true.
{{/foo}}
{{^foo}}
  output if false
{{/foo}}


来源:https://stackoverflow.com/questions/10117862/switch-case-in-mustachejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!