2011-04-16 64 views
21

我剛剛搜索'for循環',但它看起來像速度只有'foreach'。如何在速度模板中使用'for'循環?

如何在velocity模板中使用'for loop'?

+0

最好的答案是波紋管的折,通過@serg:http://stackoverflow.com/a/5683891/299843 – redben 2014-11-12 23:13:48

回答

28

只有#foreach。你將不得不在你的上下文中迭代一些東西。例如。使bar可那是某種類型的數組或Collection

#foreach ($number in [1..34]) 
    $number 
#end 
+0

//謝謝!我不明白他們爲什麼沒有最基本的循環! – Moon 2011-04-16 01:06:47

+4

foreach是最基本的一種循環。因爲是先進的。 – 2011-04-18 16:05:45

+0

請注意,Velocity中的範圍是包含的,所以第二個示例將循環34次,'$ number'從1到34. – Starwarswii 2017-07-25 14:25:02

35

想添加foreach循環內部的迭代信息可以從訪問:或者,如果你想遍歷一個數字範圍

#foreach ($foo in $bar) 
    $foo 
#end 

特別$foreach屬性:

#foreach ($foo in $bar) 
    count: $foreach.count 
    index: $foreach.index 
    first: $foreach.first 
    last: $foreach.last 
#end 

(我最後一次檢查last包含一個錯誤,雖然)

+0

正是我需要的。我需要在我的模板中編寫索引。感謝這篇文章! – 2013-05-26 03:56:29

+2

如果你遇到Velocity 1.6(Confluence使用的fe),只有'$ velocityCount'和'$ velocityHasNext'可用(http://velocity.apache.org/engine/releases/velocity-1.6/user- guide.html#Loops) – sendmoreinfo 2014-06-17 07:21:10

+0

你也可以從'$ foreach.parent.whatever'的嵌套循環中獲得這些變量,例如'$ foreach.parent.parent.index'從三重嵌套的foreach循環中獲取外部循環的索引。 – Starwarswii 2017-07-25 14:23:00

4

我找到了解決方案,當我試圖循環列表。 將該列表放入另一個類中,併爲列表obj創建getter和setter。 例如

public class ExtraClass { 
    ArrayList userList = null; 

    public ExtraClass(List l) { 
     userList = (ArrayList) l; 
    } 

    public ArrayList getUserList() { 
     return userList; 
    } 

    public void setUserList(ArrayList userList) { 
     this.userList = userList; 
    } 

} 

然後,對於速度環境,將Extraclass作爲輸入。 例如。

ExtraClass e = new ExtraClass(your list); 
VelocityContext context = new VelocityContext(); 

context.put(「data」,e); 在模板

#foreach ($x in $data.userList) 
     $x.fieldname //here $x is the actual obj inside the list 
    #end 
+0

這適用於地圖嗎? – 2016-11-21 16:47:44