【问题标题】:Is there a way in mustache to render a block if a section is present without iterating?如果一个部分存在而没有迭代,有没有办法在胡子中渲染一个块?
【发布时间】:2014-05-21 14:47:47
【问题描述】:

我有一个带有标题的部分,我只想在填充数组时才显示它,如下所示:

<h1> These are the elements in the array </h1>
<ul>
    {{#myArray}}
    <li>{{name}} - {{value}}</li>
    {{/myArray}}
</ul>

只有在填充了myArray 时,我才能呈现&lt;h1&gt;

如果我将它放在 # 部分中,它会为数组中的每个元素呈现一次,这不是我想要的。

这样做的正确方法是什么?

【问题讨论】:

  • 这样才是正确的
  • “正确”的方法是在渲染之前准备好你的视图,或者用方法传递一个对象:)

标签: html mustache mustache.php


【解决方案1】:
{{#myArray.length}}
     <h1> These are the elements in the array </h1>
{{/myArray.length}}

.length 将为空数组返回 0,因此我们获得了真正的假值。

DEMO

在 PHP 方面:

{{#myArray.0}}
     <h1> These are the elements in the array </h1>
{{/myArray.0}}

【讨论】:

  • 它不起作用,可能是因为我通过 php 使用 mustache,这意味着数组没有 .length 方法。
  • 更新了答案。在结束标记处有一个额外的 # 之前
  • 你能试试这个吗:{{#myArray.0}},我已经更新了我的答案
  • 好的,{{#myArray.0}} 可以,谢谢。我会接受答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-19
  • 2022-08-24
相关资源
最近更新 更多