如何处理 mustache 模板中的字符串或字符串数​​组 [英] How to handle string or array of strings in mustache template

查看:39
本文介绍了如何处理 mustache 模板中的字符串或字符串数​​组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于在我的应用程序(或更准确地说是 Hogan)中使用 mustache 模板的简单/初学者问题.我使用的 API 有时返回一个字符串,有时返回一个字符串数组.

I have a simple/beginner question for using mustache templating in my app (or Hogan more accurately). I am using an API which sometimes returns a String and sometimes returns an Array of Strings.

我知道可以将 String 包装在一个单元素数组中,但是否还有一种方法可以从 mustache 模板中处理这种可选性?

I know could wrap the String in a single-element array, but is there also a way to handle this optionality from the mustache template?

使用像
这样的普通部分<代码>{{#stringOrArray}}<li>{{.}}</li>{{/stringOrArray}}如果它只是一个字符串,则不会打印该值.

Using normal sections like
{{#stringOrArray}} <li>{{.}}</li> {{/stringOrArray}} doesn't print the value if its just a String.

推荐答案

我知道现在有点晚了,但这是我使用的:

I know it is a bit late, but here is what I use:

{{#test.length}}
    {{#test}}<li>{{.}}</li>{{/test}}
{{/test.length}}

{{^test.length}}
    <li>{{test}}</li>
{{/test.length}}

这就像特征检测.第一个代码块检查 test 是否有长度,如果有,它是一个数组(是的,我知道字符串也应该有一个 length 属性,但它们没有).它要么输出数组(如果是数组),要么不输出(如果不是).如果没有长度(即它是一个字符串或整数等),第二个块打印出 test 的值这意味着你可以使用它:

It's like feature detection. The first block of code checks to see if test has a length, if it does, it is an array (yes, I know strings are supposed to have a length property, too, but they don't). It will either output the array (if it is an array), or nothing (if it isn't). The second block prints out the value of test if it has no length (i.e. it is a string or integer etc) This means you can use it on:

var data = {
    test: "test1"
}

var data = {
    test: [ "test1", "test2", "test3" ]
}

无需设置是否为数组的标志.Mustache 会输出两者,但你不需要的会是空白的.

without having to set a flag for whether it is an array or not. Mustache will output both, but the one you don't need will be blank.

这篇关于如何处理 mustache 模板中的字符串或字符串数​​组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆