Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在小胡子模板中处理IF语句?_Javascript_Templates_Mustache - Fatal编程技术网

Javascript 如何在小胡子模板中处理IF语句?

Javascript 如何在小胡子模板中处理IF语句?,javascript,templates,mustache,Javascript,Templates,Mustache,我在用胡子。我正在生成通知列表。通知JSON对象如下所示: [{"id":1364,"read":true,"author_id":30,"author_name":"Mr A","author_photo":"image.jpg","story":"wants to connect","notified_type":"Friendship","action":"create"}] 使用mustache,我如何根据通知类型&操作执行if语句或case语句 如果notified\u type==

我在用胡子。我正在生成通知列表。通知JSON对象如下所示:

[{"id":1364,"read":true,"author_id":30,"author_name":"Mr A","author_photo":"image.jpg","story":"wants to connect","notified_type":"Friendship","action":"create"}]
使用mustache,我如何根据
通知类型
&
操作
执行if语句或case语句

如果
notified\u type==“友谊”
render

如果
notified\u type==“其他&&action==“邀请”
render


这是如何工作的?

通常,您使用
语法:

{{#a_boolean}}
  I only show up if the boolean was true.
{{/a_boolean}}

我们的目标是尽可能多地将逻辑移出模板(这是有意义的)。

胡须模板在设计上非常简单;甚至还说:

无逻辑模板

因此,一般的方法是使用JavaScript执行逻辑并设置一组标志:

if(notified_type == "Friendship")
    data.type_friendship = true;
else if(notified_type == "Other" && action == "invite")
    data.type_other_invite = true;
//...
然后在模板中:

{{#type_friendship}}
    friendship...
{{/type_friendship}}
{{#type_other_invite}}
    invite...
{{/type_other_invite}}
如果您想要一些更高级的功能,但又想保持小胡子的简单性,您可以看看:

Handlebar提供了必要的功能,让您能够有效地构建语义模板,而不会遇到任何挫折

胡子模板与车把兼容,因此您可以使用胡子模板,将其导入车把,并开始利用额外的车把功能


我有一个简单而通用的方法来执行key/value if语句,而不是仅在mustache中执行boolean语句(并且以非常可读的方式!):

有了这个黑客,一个像这样的物体:

var contact = {
  "id": 1364,
  "author_name": "Mr Nobody",
  "notified_type": "friendship",
  "action": "create"
};
{{#notified_type=friendship}}
    friendship…
{{/notified_type=friendship}}

{{#notified_type=invite}}
    invite…
{{/notified_type=invite}}
在转换之前将如下所示:

var contact = {
  "id": 1364,
  "id=1364": true,
  "author_name": "Mr Nobody",
  "author_name=Mr Nobody": true,
  "notified_type": "friendship",
  "notified_type=friendship": true,
  "action": "create",
  "action=create": true
};
您的胡子模板将如下所示:

var contact = {
  "id": 1364,
  "author_name": "Mr Nobody",
  "notified_type": "friendship",
  "action": "create"
};
{{#notified_type=friendship}}
    friendship…
{{/notified_type=friendship}}

{{#notified_type=invite}}
    invite…
{{/notified_type=invite}}

只要看一下小胡子文档,它们就支持“倒排部分”,在其中它们表示

如果键不存在、为false或为空列表,则将呈现它们(反转部分)


这增加了胡须数据,但这是一种可用且可读的方法,值得考虑平等示例真的很有用!在显示如何判断是否为真以及如何判断是否为假方面,这项工作可能会重复!这个答案实际上比公认的答案更适合我,因为我想在“jira自动化”中使用它“使用胡子的插件。这是答案。这个答案没有错,但正确/更好的答案是。”