问题
I have the following code which contains about 12 items but I only need to retrieve the first item. How can I display the first item in my list?
My code is:
<#list analysttest.rss.channel.item as item>
<div>
<h3 class="bstitle">${item.title}</h3>
<span class="bsauthor">${item.author}</span>
<span>${item.pubDate}</span>
<p>${item.description}</p>
</div>
</#list>
回答1:
analysttest.rss.channel.item[0]
gives the fist item, which you can #assign
to a shorther name for convenience. Note that at least 1 item must exist, or else you get an error. (Or, you can do something like <#assign item = analysttest.rss.channel.item[0]!someDefault>
, where someDefault
is like ''
, []
, {}
, etc, depending on what you need. There's even a shorter <#assign item = analysttest.rss.channel.item[0]!>
form, which uses a multi-typed "generic nothing" value as the default... see in the Manual.)
Listing is also possible, though odd for only one item: <#list analysttest.rss.channel.item[0..*1] as item>
, where *1
means at most length of 1 (requires FreeMarker 2.3.21 or later). This works (and outputs nothing) even if you have 0 items.
回答2:
<#assign item = analysttest.rss.channel.item[0]>
<div>
<h3 class="bstitle">${item.title}</h3>
<span class="bsauthor">${item.author}</span>
<span>${item.pubDate}</span>
<p>${item.description}</p>
</div>
来源:https://stackoverflow.com/questions/35468941/how-can-i-get-the-first-item-in-a-list-using-free-marker