Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

velocity directives add whitespace too?

I've just learned that with apache velocity the directives add to the whitespace as well.

So for example:

#foreach ($record in $rows)
#foreach($value in $record)
$value  
#end

#end

With something like this I end up getting extra lines for the #foreach statements, the #end statements, etc.

This isn't what I want, so I found I could block comment at the end of the lines like so:

#foreach ($record in $rows)#*
*##foreach($value in $record)#*
*#$value    #*
*##end

#end

But this is pretty ugly to read. Is there any way to tell the velocity engine to not format my directives?

Maybe I'm doing something else wrong?

Thanks.

like image 888
javamonkey79 Avatar asked Dec 13 '11 19:12

javamonkey79


2 Answers

I think you're stuck with it (see Velocity Whitespace Gobbling article) although line comments would be a little tidier:

#foreach ($record in $rows)##
#foreach($value in $record)##
$value    ##
#end

#end

Or you could just squeeze everything onto one line:

#foreach($record in $rows)#foreach($value in $record)${value}#{end}#{end}
like image 136
Edd Avatar answered Sep 28 '22 04:09

Edd


This is actually common to almost all templating languages and the reasoning comes directly from simplified processing. Consider the following example (this is actually GSP used by Grails but the idea is the same):

<g:each var="x" in="exes">
    ${x.y}
</g:each>

The way this is processed is that first a tag (or in Velocity's case, directive) is identified. Because the tag/directive itself contains instructions for processing the tag's body, the tag/directive marks are removed and all the content immediately after the starting mark and immediately before the ending mark is used as the target for the processing. This includes all the whitespace, because cleaning the output beforehand would be a lot more difficult.

This of course doesn't mean that you can't do it, as Edd points out or that this would be the most sensible design choice in the first place, but sometimes doing things more simply is more important than generating beautiful markup - after all, most if not all markup processors don't really care if you have <p>some\ncontent</p> or <p>some\n\n\n\t\tcontent</p>.

like image 25
Esko Avatar answered Sep 28 '22 06:09

Esko