English 中文(简体)
Mustache模板: 如何只为非豁免名单生产一个区块。
原标题:Mustache templates: How to output a block only once for non-empty lists
  • 时间:2012-04-11 09:05:30
  •  标签:
  • mustache

如果我的名单空洞,我就想得出这样的结果:

<div id="some-id">
</div>

如果我的名单上没有发言,我就想这样做:

<div id="some-id">
  <ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>etc</li>
  </ul>
</div>

请注意,我生产了<代码><ul>和</ul> tags, 最多一次是,但仅限于该名单为非豁免。

下面的法典与我如何在公共卫生和社会福利部中这样做密切相关,但显然是错误的:

<div id="some-id">
{{#items}}
  <ul>
{{/items}}

{{#items}}
    <li>{{name}}</li>
{{/items}}

{{#items}}
  </ul>
{{/items}}
</div>

如果<代码>项目为3个项目清单,Im将获得3个<代码><ul> s——显然不是我想要的。

我的理解是,我可以把一些其他钥匙设定为蓝色旗(hasItems,但这可能是多余的。

难道我能够只为一次非豁免名单而拿出一个障碍的更明智的方法吗?

最佳回答
问题回答

如果您不希望或能够改革其数据或排气发动机,你也可以检查<代码>项目。 <代码><ul> tags. 有些人这样做,但肯定是马克斯回答的替代办法。

{{#items.length}}
    <ul>
        {{items}}
            <li>{{name}}</li>
        {{/items}}
    </ul>
{{/items.length}}

其他两个答案不利于鲁比执行Mustache。 我的解决办法是,作为模板的一部分,再分配一个参数。

template = <<EOF
{{#has_items}}
<ul>
    {{#items}}
        <li>{{.}}</li>
    {{/items}}
</ul>
{{/has_items}}
EOF
items = [ one ,  two ,  three ]
context = { items: items, has_items: items.any? }
Mustache.render(template, context)




相关问题
iteration on couchapp

i had write this on mustache.html on couchapp **{{%IMPLICIT-ITERATOR iterator=i}} {{#example}} hallo {{i}} {{/example}}** with this array { "example": ["alpha","beta","gamma","delta"] } but ...

how do I get my mustache.js template file included?

I m working with mustache.js for the first time. All the examples I m finding seem to talk about putting everything inline, but I want my templates in external files so they can be used in multiple ...

Mustache partials and code reuse

I m getting the hang of mustache for a project I ve started during the weekend. I m using the PHP implementation. I have, however a couple of inquiries as I m not used to the system. How do you ...

Timeout in a Couchapp list when using mustache

I have a simple list view in which I (try to) use mutache to render the output of a list containing 5 results. function(head, req) { var row, mustache = require("vendor/couchapp/lib/mustache....

Is there anything I can t do with mustache?

I m evaluating http://github.com/janl/mustache.js and I m thinking about how it will work in general over time with a time. If I just build a giant object, is mustache sufficient to transform it into ...

热门标签