How can I get the first item in a list using free marker?

非 Y 不嫁゛ 提交于 2019-12-22 04:44:12

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!