Mustache null value

问题描述 投票:3回答:2

我有一个对象数组,这些对象的键的值可以为true,false或null。

var a = [
            {
                something: true
            },
            {
                something: false
            },
            {
                something: null
            }
        ];

并且小胡子应该以不同的方式涵盖所有这些情况。

例如,为真,应打印:

 <a>true</a>

为假:

 <p>false</p>

并且为空:

 <span>null</span>

是否有办法为小胡子中的3种不同类型的值编写if / else语句?

javascript mustache
2个回答
1
投票

我已经使用过Moustache函数来解决它。您可以向对象添加一个方法,该方法将传递给Mustache.render方法:

基本上,您需要遍历该对象以添加新方法,所以最终会得到如下所示:

var a = [
            {
                something: true,
                somemethod: function () {
                    return function (text) {
                        if (this.something === null) {
                            return "<p>" + text + "</p>";
                        } else if (!this.something) {
                            return "<a>" + text + "</a>";
                        } else {
                            return "<span>" + text + "</span>";
                        }
                    }
                }
            },
            {
                something: false,
                somemethod: function () {
                    return function (text) {
                        if (this.something === null) {
                            return "<p>" + text + "</p>";
                        } else if (!this.something) {
                            return "<a>" + text + "</a>";
                        } else {
                            return "<span>" + text + "</span>";
                        }
                    }
                }
            }
        ];

稍后,您可以在模板中使用以下内容:

{{#somemethod}}this text will be used{{/somemethod}}

1
投票

更简单的方法是这样的:

{{#parentId}}{{.}}{{/parentId}}{{^parentId}}null{{/parentId}}

在上面的示例中,如果parentId有值,则输出,如果没有,则输出文字文本null

© www.soinside.com 2019 - 2024. All rights reserved.