Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
like image 493
Spanky Avatar asked Feb 17 '16 22:02

Spanky


People also ask

What is eval in FreeMarker?

eval. This built-in evaluates a string as an FTL expression. For example "1+2"? eval returns the number 3. (To render a template that's stored in a string, use the interpret built-in instead.)

What is C in FreeMarker?

c (when used with numerical value) This built-in converts a number to string for a "computer language" as opposed to for human audience. That is, it formats with the rules that programming languages used to use, which is independent of all the locale and number format settings of FreeMarker.

How do you create a list on FreeMarker?

FreeMarker doesn't support modifying collections. But if you really want to do this in FreeMarker (as opposed to in Java), you can use sequence concatenation: <#assign myList = myList + [newItem]> . Here you create a new sequence that wraps the two other sequences.

What is the use of FreeMarker jar?

Apache FreeMarker™ is a template engine: a Java library to generate text output (HTML web pages, e-mails, configuration files, source code, etc.) based on templates and changing data.


2 Answers

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.

like image 55
ddekany Avatar answered Oct 12 '22 02:10

ddekany


<#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>
like image 26
Kalman Avatar answered Oct 12 '22 02:10

Kalman