Search code examples
javascripthtmlxssfreemarker

Multi-language auto-escape in Freemarker


I recently turned on auto-escaping in Freemarker and change my .ftl files to .ftlh to make sure they get formatted/escaped as HTML. However, this means that any inline <script> or <style> tags get HTML escaped, which is not what I want. I can solve the problem by doing this:

<script>
    [#outputformat "JavaScript"]
         jQuery(".stuff").blah();
    [/#outputformat]
</script>

This works, but it seems like a lot of work to add this wrapper around the contents of every script tag. It seems it would make sense to have a OutputFormat that is smart enough to detect script/style tags and use the right format, or alternatively custom tags that have the same effect as the above. Something like:

[@smartscript]
    jQuery(".stuff").blah();
[/@smartscript]

Does anything like this (or anything else that solves this problem) already exist? I haven't been able to find anything.


Solution

  • Other than pre-processing templates in a custom TemplateLoader (which wraps another TemplateLoader and filters the Reader returned by it), there's no solution for this currently. Macros won't help either, because #outputformat doesn't have runtime effect. It just associates sections of the FTL source code with an output format.