phil.e.b
phil.e.b

Reputation: 2621

Thymeleaf encoding issues with javascript (using spring mvc)

I am using spring mvc + thymleaf v3 and have an encoding issue when it comes to some data in the javascript defined in the html head section. Here is the javascript as defined in the head :

function addtab(count) {

            var closetab = '<a href="" id="close'+count+'" class="close">&times;</a>';
            $("#tabul").append('<li id="t'+count+'" class="ntabs">Tab '+count+'&nbsp;&nbsp;'+closetab+'</li>');
            $("#tabcontent").append('<p id="c'+count+'">Tab Content '+count+'</p>');

The problem is that the apostrophes used to escape the string for the html attributes only, get replaced by the html encoding ' and results in the following when received by browser client :

function addtab(count) {

            var closetab = '<a href="" id="close&#39;+count+&#39;" class="close">&times;</a>';
            $("#tabul").append('<li id="t&#39;+count+&#39;" class="ntabs">Tab '+count+'&nbsp;&nbsp;'+closetab+'</li>');
            $("#tabcontent").append('<p id="c&#39;+count+&#39;">Tab Content '+count+'</p>');

notice that only the html attribute values apostrophes have been html encoded, the apostrophes in the value section of the html tag are ok.

Here is my web-servlet section containing the config for thymeleaf :

<beans:bean id="templateResolver" class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
  <beans:property name="prefix" value="/WEB-INF/views/" />
  <beans:property name="suffix" value=".html" />
  <beans:property name="characterEncoding" value="UTF-8" />
  <beans:property name="templateMode" value="HTML5" />
</beans:bean>

<beans:bean id="templateEngine" class="org.thymeleaf.spring3.SpringTemplateEngine">
  <beans:property name="templateResolver" ref="templateResolver" />
</beans:bean>

  <beans:bean class="org.thymeleaf.spring3.view.ThymeleafViewResolver">
    <beans:property name="templateEngine" ref="templateEngine" />
    <beans:property name="characterEncoding" value="UTF-8" />
    <beans:property name="contentType" value="text/html; charset=UTF-8" />
  </beans:bean>

Is there something I am missing about the setup in thymleaf or spring for encoding of the rendered pages ?

I have tried filters but these are only for incoming data and have read many posts but am unable to find a solution.

Thanks.

Upvotes: 2

Views: 1525

Answers (1)

phil.e.b
phil.e.b

Reputation: 2621

ah ben tbnk. I just externalized the javascript in a seperate file and included it in the html file which is being passed through thymeleaf and this solved the problem.

ouch, many hours lost to such a simple solution. hope this can help someone else that may come across this issue.

Upvotes: 2

Related Questions