问题描述
如果我的列表为空,我想输出以下内容:
If my list is empty, I want to output this:
<div id="some-id">
</div>
如果我的列表非空,我想输出以下内容:
If my list is non-empty, I want to output this:
<div id="some-id">
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>etc</li>
</ul>
</div>
请注意,仅当列表为非空时,我最多输出一次<ul>
和</ul>
标记 .
Note that I output the <ul>
and </ul>
tags at most once, and only if the list is non-empty.
以下代码与我在PHP中的实现方式非常接近,但显然是错误的:
The following code is close to how I would do this in PHP, but is obviously wrong:
<div id="some-id">
{{#items}}
<ul>
{{/items}}
{{#items}}
<li>{{name}}</li>
{{/items}}
{{#items}}
</ul>
{{/items}}
</div>
如果items
是3个项目列表,我将得到3个<ul>
-显然不是我想要的.
If items
is a 3 item list, I'm going to get 3 <ul>
's - obviously not what I want.
我意识到我可以将其他键设置为布尔标志(也许是hasItems
),但这感觉很多余.
I realise I could set some other key as a boolean flag (hasItems
, perhaps), but this feels redundant.
对于非空列表,我是否可以只输出一次块呢?
Is there a more elegant way I can output a block only once for a non-empty list?
推荐答案
您可以使用非false值. name
必须是items
You could use non-false values of a section. name
would have to be an object inside of items
data = { 'items' : { 'name' : ["Item 1", "Item 2", "etc"] } };
您的模板如下所示:
<div id="some-id">
{{#items}}
<ul>
{{#name}}
<li>{{.}}</li>
{{/name}}
</ul>
{{/items}}
</div>
这是jsFiddle上的一个示例,该示例显示具有名称且不带- http:/的items
对象的呈现. /jsfiddle.net/maxbeatty/fpQwk/
Here's an example on jsFiddle showing the rendering of an items
object with names and without -- http://jsfiddle.net/maxbeatty/fpQwk/
这篇关于小胡子模板:如何为非空列表仅输出一次阻止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!