JavaScript escaping on strings that contain paths has unexpected results
See original GitHub issueThe original reference to this comes from: http://forum.thymeleaf.org/is-being-escaped-when-inlined-in-javascript-td4025110.html
In summary:
I have the following code that is not behaving as expected:
<script th:inline="javascript"> var url = /*[[ @{'/sources/' + ${source.name} + '/upload'} ]]*/ '/sources/xxx/upload'; </script>
The rendered result is:
var url = '\/sources\/123456\/upload';
What I want is:
var url = '/sources/123456/upload';
I’m currently working around this issue with the following:
url = url.replace(//g,‘’);
It is effective but I would prefer not to have to do this.
I understand that JavaScript escaping is performed in a way that mirrors the behaviour of Apache Commons-Lang’s “StringEscapeUtils.escapeEcmaScript(…)” method, which is almost considered a de-facto standard. However, in this particular case not producing the desired result. Is it possible to disable the javascript escaping for content produced by @{} expressions? This seems like one place where the escaping will always cause problems.
Issue Analytics
- State:
- Created 11 years ago
- Comments:6 (3 by maintainers)
Top GitHub Comments
@yglodt @martintilma please note this is expected behaviour, and the generated JavaScript literals are perfectly valid (though maybe, I admit, a bit less pretty).
This happens when Thymeleaf’s JavaScript inlining capabilities use Jackson for JavaScript/JSON serialisation (which will happen if Jackson is in the classpath). JavaScript blocks appearing inside
<script>
tags should avoid including the</
sequence, in order to avoid closing the<script>
tag before they should. The way to avoid this is to escape the/
symbol like\/
, which in a JavaScript literal is 100% equivalent to/
(that’s why there is no actual issue with this behaviour, only a different appearance).When Jackson is not used, Thymeleaf’s own default serialisation method is able to determine when a
/
symbol goes after a<
and therefore only escape to\/
when this happens. But unfortunately Jackon’s escaping mechanisms are much much simpler and do not allow such conditional behaviour to be applied. So the only way to avoid accidental closing of<script>
tags inside JavaScript literals is to escape all/
characters. Thus the behaviour you observe, introduced in Thymeleaf 3.0.2 (see #536).But again, as I said, in JavaScript
"http:\/\/this\/that"
is 100% equivalent to"http://this/that"
, so besides the fact that it maybe isn’t as pretty, you should not need to apply any kind of workarounds here…This is a quite old ticket, I’m therefore closing it because IMHO there is no need to do anything (and no-escaping is already covered by
[(...)]
andth:utext
in JavaScript inlining / template mode in v3.0.Workaround: