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.

有帮助吗?

解决方案 2

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 '='.

其他提示

There are two ways you can do this with jQuery:

  1. The first is when you have the response data already, then you can put it into an element like this:

    $("#myElement").html(myData);
    
  2. The second is that you could load the data directly into the element:

    $("#myElement").load("http://myurlgoeshere.com/webservice");
    
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top