如何在 Mustache.js 中完成 if/else?
我不知道如何在小胡子中做到这一点,这似乎很奇怪。支持吗?
这是我悲伤的尝试:
{{#author}}
{{#avatar}}
<img src="{{avatar}}"/>
{{/avatar}}
{{#!avatar}}
<img src="/images/default_avatar.png" height="75" width="75" />
{{/avatar}}
{{/author}}
这显然是不对的,但文档没有提到这样的事情。甚至没有提到“else”这个词:(
另外,为什么小胡子要这样设计?这种事情被认为是不好的吗?它是否试图强迫我在模型本身中设置默认值?那么在以下情况下呢?那不可能吗?
It seems rather odd that I can't figure how to do this in mustache. Is it supported?
This is my sad attempt at trying:
{{#author}}
{{#avatar}}
<img src="{{avatar}}"/>
{{/avatar}}
{{#!avatar}}
<img src="/images/default_avatar.png" height="75" width="75" />
{{/avatar}}
{{/author}}
This obviously isn't right, but the documentation doesn't mention anything like this. The word "else" isn't even mentioned :(
Also, why is mustache designed this way? Is this sort of thing considered bad? Is it trying to force me to set the default value in the model itself? What about the cases where that isn't possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这就是您在 Mustache 中执行 if/else 的方式(完全支持):
或者在您的情况下:
在文档中查找倒置部分:
This is how you do if/else in Mustache (perfectly supported):
Or in your case:
Look for inverted sections in the docs: https://github.com/janl/mustache.js#inverted-sections
这是您在“控制器”中解决的问题,这就是无逻辑模板的要点。
这实际上比维护模板中可能会或可能不会改变的图像 URL 或其他媒体要好得多,但需要一些时间来适应。重点是要忘记模板隧道视觉,头像 img url 必然会在其他模板中使用,您是否要在 X 模板或单个 DEFAULTS 设置对象上维护该 url? ;)
另一种选择是执行以下操作:
在模板中:
但这违背了无逻辑模板的全部含义。如果这就是您想要做的,那么您需要逻辑模板并且您不应该使用 Mustache,但请给自己一个学习这个概念的公平机会;)
This is something you solve in the "controller", which is the point of logicless templating.
This is actually a LOT better then maintaining image url's or other media that might or might not change in your templates, but takes some getting used to. The point is to unlearn template tunnel vision, an avatar img url is bound to be used in other templates, are you going to maintain that url on X templates or a single DEFAULTS settings object? ;)
Another option is to do the following:
And in the template:
But that's going against the whole meaning of logicless templating. If that's what you want to do, you want logical templating and you should not use Mustache, though do give it yourself a fair chance of learning this concept ;)
您的 else 语句应如下所示(请注意
^
):在 Mustache 中,这称为“反向部分”。
Your else statement should look like this (note the
^
):In mustache this is called 'Inverted sections'.
请注意,您可以使用
{{.}}
来呈现当前上下文项。Note, you can use
{{.}}
to render the current context item.您可以在视图中定义一个助手。然而,条件逻辑有些有限。 Moxy-Stencil (https://github.com/dcmox/moxyscript-stencil) 似乎使用“参数化”帮助器解决这个问题,例如:
并在视图中:
You can define a helper in the view. However, the conditional logic is somewhat limited. Moxy-Stencil (https://github.com/dcmox/moxyscript-stencil) seems to address this with "parameterized" helpers, eg:
and in the view: