开发者

Escape a curly brace { in Velocity

开发者 https://www.devze.com 2023-02-24 22:02 出处:网络
SORRY: This is my bad. This error is due incorrect json produce and to Chrome extension \"JSONView in Chrome\". See my own answer (I had to answer this myself - as I could not delete the question anym

SORRY: This is my bad. This error is due incorrect json produce and to Chrome extension "JSONView in Chrome". See my own answer (I had to answer this myself - as I could not delete the question anymore).

I am using Velocity (Maven version 1.7 of org.apache.velocity) as templating engine, and I want output as f开发者_高级运维ollows:

{
   total : 234
}

now when I try:

{
    total : $listing.size()
}

I get an error:

Error: Parse error on line 1:
{   total : 0}
--^
Expecting 'STRING', '}'

Escape a curly brace { in Velocity

and when I try to escape the curly braces:

\{
    total : $listing.size()
\}

I get the escape characters in the final output!:

\{
   total : 234
\}


Sorry this was due incorrect JSON I was producing, which Chrome browser's extension "JSONView" pointed out to me. This was because my keys were not strings... i.e. I had:

 {total: 0}

but I should've had:

 {"total" : 0}


Indeed there is a better way of doing this.

use the accepted answer here (How to XML escaping with Apache Velocity?) to do the initial set-up

you would need to add the velocity-tools dependency as well :

<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity-tools</artifactId>
    <version>2.0</version>
</dependency>

and then you can use the escape mechanism of the Velocity Engine like this (for your case)

$esc.java("{total: 0}")

you can also checkout more escape options here(http://velocity.apache.org/tools/devel/generic/EscapeTool.html)


I ended up creating a constant ocb = { and ccb = } and using $ocb and $ccb.

I am sure there is a better way. ;)


Here is something that looks like your situation: http://velocity.apache.org/engine/devel/user-guide.html#escapinginvalidvtlreferences

UPDATE:

Try to do this first:

#set( $startbrace = "{" )
#set( $endbrace = "}" )

and then make your text this:

$startbrace
    total : $listing.size()
$endbrace
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号