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
有帮助吗?

解决方案

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}}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top