如何使用 mustache.js 中的比较来完成 if/else?

Sna*_*yes 5 jquery mustache

我在这篇文章中阅读了如何在 mustache.js 中使用 if/else 。

现在我的问题是,可以在if语句中使用比较运算符吗?

喜欢(只是我举了一个错误的例子):

{{#ItemIndex==0}}
   <td>{{ItemIndex}}</td>
{{/ItemIndex}}
{{^ItemIndex==0}}
   <td>{{ItemIndex}} *</td>
{{/ItemIndex}}
Run Code Online (Sandbox Code Playgroud)

怎么做 ?

pdo*_*926 3

你不能使用 Mustache 来做到这一点。

但是,由于您对等于 0(假)的值感兴趣,因此可以执行以下操作:

/*
Template:
{{#objs}}
    {{^ItemIndex}}
        {{ItemIndex}}*
    {{/ItemIndex}}
    {{#ItemIndex}}
        {{ItemIndex}}
    {{/ItemIndex}}
{{/objs}}"
*/

var template = "{{#objs}}{{^ItemIndex}}{{ItemIndex}}*{{/ItemIndex}}{{#ItemIndex}}{{ItemIndex}}{{/ItemIndex}}\n\n{{/objs}}"

document.getElementsByTagName('body')[0].textContent = (Mustache.render(template, {objs: [
    {
        ItemIndex: 0
    }, 
    {
        ItemIndex: 1
    },    
    {
        ItemIndex: 2
    } 
]}))

// result => 0* 1 2
Run Code Online (Sandbox Code Playgroud)

小提琴

如果您需要在模板中使用 if/else 构造并且喜欢 Mustache 语法,那么您应该查看Handlebars.js