API / Apache Velocity Interview questions
How do you escape special characters like $ and # in a Velocity template?
A backslash immediately before $ or # prevents Velocity from treating it as the start of a reference or directive, so it's printed as a literal character instead.
Price: \$19.99 Use the \#include directive to insert static files.
Escaping is only needed when the character would otherwise be parsed as VTL syntax, if a $ isn't followed by a valid identifier character, Velocity typically treats it as literal text automatically, but relying on that is fragile, so explicit escaping is the safer habit for anything user-facing.
For escaping output values rather than literal template text, such as user-supplied data that needs HTML/XML/JS-safe encoding to prevent injection, Velocity Tools ships an EscapeTool (commonly bound to $esc) with methods like $esc.html($input), which is the correct mechanism for untrusted data rather than backslash escaping.
More Related questions...