Velocity template fails to render because one of the string variable contains a $ character

Viewed 308
 "name": "$data"

I am using velocity with Java and if the value of $data contains a $ character like $abcd then the template fails to render because of the error message.

"Error rendering the template ::: HomePage : data [abcd, abcd] is missing"

How to fix this issue so I can render strings with $ character in them?

Also, tried the escape tool in java but nothing seems to work.

Edit: I have a user object coming from BE and I want to render different values for this user like $user.name, $user.address, etc. If any field say $user.name is abcd$pqr then parsing fails because of unknown variable $pqr. How to fix this issue when we have to render the data nested in object? If I do the following

#set($username = "$user.name")
"name": "$username"

then it fails with error that $user.name is missing and treats it as one and doesn't interpolate. Basically, I want to show the value of $user.name intact.

1 Answers

When defining values for Velocity, you can just use single quotes to avoid interpolation:

#set( $data = '$data' )
"name": "$data"

Or use a specific variable to display $:

#set( $d = '$' )
"name": "${d}data"

Or use a comment:

#* this is a comment *#
"name": "$#**#data"

Or use unparsed content:

"name": #[["$data"]]#
Related