Dor-Ron
Dor-Ron

Reputation: 1807

Accessing ArrayList by index using Velocity Templates

I'm passing in a HashMap with a String mapping to an ArrayList. The map contains two entries, which are ArrayLists of the same length, and I want them aligned horizontally, so I figured a foreach-range loop would work better than a foreach loop on the entries individually.

I have:

#foreach($i in [1..$entry1.size()])
    <li>
        <h3>$entry1.get($i-1)</h3>
        <video width="320" height="240" controls>
            <source src="$entry2.get($i-1)" type="video/mp4">
        </video>
    </li>
#end

Velocity just prints $entry1.get($i-1) and takes $entry2.get($i-1) literally $entry1.size() times, instead of injecting the values from the corresponding ArrayList indices.

The Velocity Documentation says:

NOTE: For the ArrayList example the elements defined with the [..] operator are accessible using the methods defined in the ArrayList class. So, for example, you could access the first element above using $monkey.Say.get(0).

And the example was:

#set( $monkey.Say = ["Not", $my, "fault"] ) ## ArrayList

Am I accessing the ArrayList correctly?

Upvotes: 1

Views: 4463

Answers (2)

user0007
user0007

Reputation: 81

I noticed that velocity isn't evaluating expression inside get() method at $entry1.get($i-1).

Try something like this :

#foreach($i in [1..$entry1.size()])
    #set($index = $i - 1)
    <li>
        <h3>$entry1.get($index)</h3>
        <video width="320" height="240" controls>
            <source src="$entry2.get($index)" type="video/mp4">
        </video>
    </li>
#end

Upvotes: 1

Dor-Ron
Dor-Ron

Reputation: 1807

So, I'm still unsure as to what was wrong with my code above... This was my work around though:

#foreach( $title in $entry1 )
  <li>
    <h3>$title</h3>
    <video width="320" height="240" controls>
      <source src="$entry2.get($foreach.index)" type="video/mp4">
    </video>
  </li>
#end

Hope it helps anyone who may run across a similar problem in the future. Would still like to know what was wrong with my initial code though!

Upvotes: 0

Related Questions