0

I am using velocity templates and need to split the output of a function into an array of sentences:


$page.getSectionCopy()

which outputs:

The first sentence. The second sentence. The third sentence. The fourth sentence.The fifth sentence. 

What I would like to achieve is the following:

<p>
The first sentence. The second sentence.
</p>
<p>
The third sentence. The fourth sentence. The fifth sentence. 
</p>

So as you can see, I need to get the first two sentences and put them in the first <p> tag.

Any help would be greatly appreciated.

steakpi
  • 953
  • 1
  • 6
  • 11

1 Answers1

0

If getSectionCopy() returns a String, I'm pretty sure you can do something like:

#set ($splitString = $page.getSectionCopy().split("\\.")) ## split takes regex - split on period.
<p>
    $splitString[0].trim().  $splitString[1].trim().
</p>
<p>
    #foreach ($sentence in $splitString)
        ## $velocityCount built in variable to count for index.  1 based, not 0 based.
        #if ($velocityCount > 2) 
            $sentence.trim().&nbsp;
        #end
    #end
</p>

Haven't tested the code.

Also, here is a related post that might help: Using velocity split() to split a string into an array doesnt seem to work

Community
  • 1
  • 1
jmrah
  • 5,715
  • 3
  • 30
  • 37
  • Thanks jrahhali, I have a split on the go now. The only thing I need now is to have a loop as I dont know how many sentences will be each time. My only constant is the first two sentences will be in the first

    tag.

    – steakpi Oct 29 '14 at 15:13
  • updated the code with a for loop. Hopefully $velocityCount works for you. – jmrah Oct 29 '14 at 15:19
  • 1
    apprently, if you are using velocity 1.7+, there is a $foreach.index (zero based) and a $foreach.count (one based). You can try these out also, if you want. Reference here: http://stackoverflow.com/questions/7847432/how-to-get-a-zero-based-count-in-a-velocity-foreach-loop – jmrah Oct 29 '14 at 15:26