using freemarker with javascript ES6 Template Strings

freemarker, javascript, template-engine

Solution

Update: Since FreeMarker 2.3.28 you can configure FreeMarker to use `[=exp]` instead of `${exp}`, by setting the `interpolation_syntax` configuration setting to `square_bracket` (in the Java API: `Configuration cfg; ... cfg.setInterpolationSyntax(Configuration.SQUARE_BRACKET_INTERPOLATION_SYNTAX)`). Then `${exp}` is just static text for FreeMarker. Do not confuse this setting with the `tag_syntax` setting, which also can have `square_bracket` value, but is independent of the interpolation syntax (but you may prefer setting both to `square_bracket`). See also: https://freemarker.apache.org/docs/dgui_misc_alternativesyntax.html

Outdated answer: FreeMarker's syntax is not configurable unfortunately (nor is the ES6 template syntax, I assume). Because that would be the real solution, to configure it to use something else instead of `$`. You can create a poor man's implementation of that with a custom `TemplateLoader` implementation that just delegates to another `TemplateLoader`, except that it adds a filter to the `Reader` it returns, and with that it modifies the template on-the-fly. It would replace `${`-s with `$<#-- -->{`, and `@{`-s with `${`. So then your original template can be something like `${forES6} @{forFM}`. This have quite a few drawbacks, like the column numbers in FreeMarker error positions will be displaced, and the Eclipse plugin and some other tools won't work.

Problem

Freemaker templates render variables with the following syntax: ${name} Javascript ES6 template strings have a similar syntax ${name} The problem is that when freemarker runs on the server, it will try to render the templates in the javascript code, because Freemarker thinks that it has encountered a variable (when in fact it is a javascript template that should be rendered on the client). Recommnedation on how to handle this? One way is to wrap all the JS in a freemarker comment (so it is never evaluated), or put the JS code in a seprate file (not inlined in the html page) so that it is never evaluated by freemarker.

Original source