Search code examples
javascriptescapingquotesthymeleaf

how to escape single quote in thymeleaf and javascript code


I need to update an html DOM using javascript, by inserting a link that will invoke a javascript function when a user clicks the link in a Thymeleaf template.

$.ajax({
  type: "GET",
  beforeSend: function(xhrObj){
    xhrObj.setRequestHeader("Content-Type","application/json");
    xhrObj.setRequestHeader("Accept","application/json");
  },
  url: "/users/list",
  dataType:"json",
  success: function( data,  textStatus,  jqXHR){
        var table = $("#userlist").children();
        for(i in data){
            table.append("<tr><td><a onclick='user_see("+data[i].userId+")' th:href='#'>"+data[i].userId+"</a></td><td>"+data[i].firstName+"</td><td>"+data[i].lastName+"
            }
   }
});

It turns out Thymeleaf replaces single quotes with double quotes. I have tried escaping the singe quote with \' but I only end up with a Thymeleaf parse error when the page is loaded

Thu Oct 30 17:55:21 EAT 2014 There was an unexpected error (type=Internal Server Error, status=500). Exception parsing document: template="users/list",

How can I escape the single quote?


Solution

  • The safest thing would be not to append HTML as a string, but use the DOM API instead. It's wordier, but avoids the quoting issues:

     data.forEach(function(datum) {
        var tr = document.createElement('tr');
        var td = document.createElement('td');
        var a = document.createElement('a');
        a.onclick = function() { user_see(datum.userId); };
        a.setAttribute('th:href', '#');
        a.innerHTML = datum.userId;
        tr.appendChild(td);
        td = document.createElement('td');
        td.innerHTML = datum.firstName;
        tr.appendChild(td);
        td = document.createElement('td');
        td.innerHTML = datum.lastName;
        tr.appendChild(td);
        table.appendChild(tr);
    }