Search code examples
javascriptjqueryblueimp

how to render html using javascript


I have a javascript engine(using jquery) that needs to render a html which comes as a output from a third party server (REST API). The response contains plain text and occasional html elements like <b>, <p> <br> etc which I want to render as html output. (and not literally as <b>, <p> etc)

Is there a way ?

Here is what I am doing - in pseudo code. Note : I am using blueimp javascript template to generate code.

jQuery.get({
    url: 'someRESTfulURL/id',
    method: 'get',
    success: function(resp) {
      //resp contains html elements like <b> etc
      var data = {title: resp.title, content: resp.content};
      $("#maindiv").html(tmpl("text-tmpl", data)); 
    }
});

<script type="text/x-tmpl" id="text-tmpl">
    <h3>{%=o.title%}</h3>
    <p>{%=o.content%}</p>
</script>

<html><body><div id='maindiv'></div></body></html>

The javascript template is encoding the html characters and hence the problem. Is there a way I can use this template and still render the html chars.


Solution

  • You have to prevent the escaping of HTML special characters. Try this:

    <script type="text/x-tmpl" id="text-tmpl">
        <h3>{%#o.title%}</h3>
        <p>{%#o.content%}</p>
    </script>
    

    The difference is just the '#' instead of the '='.