Velocity Templates - New Line

≡放荡痞女 提交于 2019-12-04 17:44:14

问题


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?


回答1:


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 />.




回答2:


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>



回答3:


Are you using Velocity to generate HTML content? In that case remember that you need to use <br> not a newline.

If you actually want a new line character you just put the actual new line character, i.e. press enter. There is no escape sequences like \n in Velocity.




回答4:


If you are using Velocity 1.5 or later, you can also just put the new line in there:

#set( $foo = "this has a 
line break" ) 



回答5:


It might be easiest to simply use the Velocity EscapeTool.

See this link: https://velocity.apache.org/tools/releases/2.0/javadoc/org/apache/velocity/tools/generic/EscapeTool.html#getNewline%28%29

Example Usage: Line Break Here: $esc.newline This is on a new line.



来源:https://stackoverflow.com/questions/4549427/velocity-templates-new-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!