velocity-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Geir Magnusson Jr." <ge...@optonline.net>
Subject Re: Foreach macro
Date Tue, 24 Oct 2000 11:57:21 GMT
Theo Keyzer wrote:
> 
> Hi,
> 
> What effect will the following have (3 data queries?) and is
> it possible to get rid of the (if) ea. not have the macro
> process if there is no data items.
> 
> #loop ($data.Getsome)
> 
> #macro (loop $list)
>   #if ($list) <table>
> 
>   #foreach $row in $list
>     <tr><td>$row</td></tr>
>   #end
> 
>   #if ($list) </table>
> #end

If I understand the question, couldn't you have the following : 

#macro( loop $list )
	#if ($list)
		<table>
		#foreach( $row in $list )
			<tr><td>$row</td></tr>	
		#end
		</table>
	#end
#end

This would only work if wanted to catch a null reference for $list.

A kludgier way would be to put the <table> inside the #foreach with a
counter :

#macro( loop $list )
	#set $i = 0
	
	#foreach( $row in $list )
		#if( $i == 0 )
			<table>
		#end
		<tr><td>$row</td></tr>	
		#set $i = $i + 1
	#end
	
	#if( $i > 0)
		</table>
	#end	
#end

But thats a pain.

Another way, which addresses the same problem is that any Object[] 
pushed into the context should be wrapped in an ArrayIterator, so maybe
you can depend on that. (I just got back from vacation, so not sure how
this works yet...)

#macro( loop $list )
	#if ($list.hasNext() )
		<table>
		#foreach
		</table>
	#end
#end

Now, this isn't a 'public' interface in the sense that it was meant for
the designer, but you certainly bring up a good idea.  Maybe we add
something to ArrayIterator like public boolean hasElements() to do
this?  Or elementCount()? And document it.

[What do we do if $list is a null reference?]

geir

-- 
Geir Magnusson Jr.                               geirm@optonline.com
Dakota tribal wisdom: "when you discover you are riding a dead horse,
the best strategy is to dismount."

Mime
View raw message