Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Velocity Templates - New Line

I've been working with Apache's Velocity engine and a custom template.
The thing is, that I haven't been able to generate a String with the corresponding line breaks. I tried almost everything that I found, such as using $esc.n and $esc.newline (I'm already using escape tools on my project) but it seems that the version I'm currently using doesn't support it (1.4), checked if putting '\n', '\\n' and even '\\\n' would work, but same thing.

Does anyone have any solution to this?

like image 482
LdSe Avatar asked Dec 28 '10 20:12

LdSe


2 Answers

We had issues with newlines and ended up putting a property on the VelocityContext:

VelocityContext ctx = new VelocityContext();
ctx.put("newline", "\n");

Then, wherever we needed to use a newline, we would reference the context variable:

$newline

We use this in cases where we need to replace newlines in a string with <br />.

like image 107
jt. Avatar answered Oct 05 '22 18:10

jt.


I needed a new line for generating javascript. Well, I didn't need it of course, but it made reading the generated code easier while developing. In this case, I just set a variable so that the Velocity was easier to read. This is all you need:

Velocity Code:

#set( $newline="
")
#set( $jsCode = "var bling='blang';{$newline}var bark='bite';{$newline}" )
<script>
$jsCode</script>

Result:

<script>
var bling='blang';
var bark='bite';
</script>
like image 26
ClubbedAce Avatar answered Oct 05 '22 19:10

ClubbedAce