胡子语法:有条件地打印HTML

问题描述 投票:1回答:1

我有一个形式的JSON:

{
  "repo": [
    { "type": "A" },
    { "type": "B" },
    { "type": "B" },
    { "type": "C" }
  ]
}

我使用Mustache语法在HTML中打印,如下所示

{{#repo}}
  {{type}}
{{/repo}}

现在,基于A,B或C类型,我需要使用给定的映射有条件地打印某些单词:

"A" = "Small"
"B" = "Medium"
"C" = "Big"

有什么办法可以用胡子做到这一点吗?

var txt = '{"repo": [{ "type": "A" },{ "type": "B" },{ "type": "B" },{ "type": "C" }],"typeMapped":{},"types": {"A": "Small",   "B": "Medium","C": "Big"}}';

var obj = JSON.parse(txt);

obj.typeMapped = function () {
    return obj.types[obj.type] || "";
  }
html json mustache
1个回答
2
投票

像这样:

{
  "repo": [
    { "type": "A" },
    { "type": "B" },
    { "type": "B" },
    { "type": "C" }
  ], 
  "typeMapped": function () {
    return this.types[this.type] || "";
  }, 
  "types": {
    "A": "Small",
    "B": "Medium",
    "C": "Big"
  }
}
{{#repo}}
  {{type}}: {{typeMapped}}
{{/repo}}
© www.soinside.com 2019 - 2024. All rights reserved.