velocity-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Barbara Baughman <baugh...@utdallas.edu>
Subject Re: Dereferencing a Reference
Date Wed, 07 Jun 2006 21:05:21 GMT
Try using a Map interface object like HashMap or TreeMap.

HashMap<String, String> hm=new HashMap<String, String>();
hm.put("a","apple");
hm.put("b","blueberry");
ctx.put("map",hm);

Then in Velocity:

#foreach ($key in $map.keySet())
  $key  $map.get($key)
#end

Barbara Baughman
X2157

On Wed, 7 Jun 2006, Keith R. Bennett wrote:

> What Velocity template code can I use to get a list of keys and iterate
> over that list, getting the value corresponding to each key?  Here is
> what I've tried so far:
>
> Before calling Velocity, I place the list of keys plus each key/value
> pair in the context.  For example:
>
> --
> String [] letters = { "a", "b" };
> context.put("letters", letters);
> context.put("a", "apple");
> context.put("b", "blueberry");
> --
>
> In the template I have:
>
> --
> $a
> $b
>
> #foreach ( $letter in $letters )
> $letter
> ${${letter}}        ## <-- This is the line in question
> #end
> --
>
> However, the output is:
>
> --
> apple
> blueberry
>
> a
> ${a}
> b
> ${b}
> --
>
> The ${a} and ${b} above should be apple and blueberry instead.
>
> What can I use in the line in question to dereference the reference?
>
> Also, is there a better way of accomplishing my goal, which is this?:
>
> I have an app that will have database records of arbitrary type.  The
> record metadata allows me to get the field names with which to populate
> the Velocity context.  The record itself has, of course, the data.  I
> want the Velocity template designer to be able to loop through the
> fields in the database record without knowing its format at design time,
> as in:
>
> #foreach ($fieldName in $field_names)
>   <$fieldname>
>     ...  ## put the field's value here, as in my vain attempt above
>          ## with ${${fieldname}}
>   </$fieldname
> #end
>
> The data record is not a Java object with named field member variables,
> so I can't use the Java Bean approach.  Perhaps I could create a class
> dynamically at runtime, but I expect this would be overkill.
>
> Thanks for any help you can offer.
>
> - Keith
>
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: velocity-user-unsubscribe@jakarta.apache.org
> For additional commands, e-mail: velocity-user-help@jakarta.apache.org
>
>

---------------------------------------------------------------------
To unsubscribe, e-mail: velocity-user-unsubscribe@jakarta.apache.org
For additional commands, e-mail: velocity-user-help@jakarta.apache.org


Mime
View raw message