Search code examples
javavelocity

Is it possible to insert HTML directly into the velocity template with a java variable?


Consider the following java variable declaration:

String s = "Please follow us on Facebook <a href=\"https://facebook.com/u/myuser\"> here</a>";

And consider the following Velocity template:

<html>
    <body>
    ...
    <div>$!s</div>
    ...
    </body>
</html>

Would this work as expected? Or rather, is it possible to insert HTML directly into the DOM via a java variable?

I'm assuming no - I would guess that the HTML characters would get escaped.

I'm working on creating some generic templates to re-use as much as possible so I'll probably end up testing this myself but figured I'd ask to see if I can save myself a bit of time if anyone knows off the top of their head. Additionally, I couldn't find any information on this in the velocity docs or stackoverflow already.


Solution

  • Yes, it is possible.

    Velocity does not escape HTML itself as it is not indended solely for HTML. Generally, it does not know what type of text you generate with it.

    Velocity includes an escape tool that can be used to explicitly escape what you need: https://velocity.apache.org/tools/1.4/generic/EscapeTool.html

    If you are going to use Velocity to generate HTML, I'd recommend you to only use String variables and escape all the variables you pass to it for output. If you need some variables to not be escaped, use a whitelist (i.e. the explicit list of the names of variables you do not escape in your escaper).

    This approach will allow to implement 'escape by default' policy.