Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get HTML from JSON data, Using MUSTACHE?

Tags:

json

php

mustache

I am using JSON and MUSTACHE, for templates in my new site. But I don't know how can i get the HTML out of json data. I am using PHP in backend, which is working as API provider. I am very new to this concept. Evey help and suggestions are Welcome.

Thanks.

Code I am using::

<script>
// this is for base
    this.get(/\#\/(.*)/, function (){
      var send_url = '<?php echo $url?>sammy/' + this.params['splat'];
      var context = this;
      $.getJSON(send_url, function(data) {
        var template = data.template;
        context.renderEach('<?php echo $url?>mustache_templates/' + template + '', data.data).swap();
      });
    });
</script>

JSON data is like::

{"menu": {
  "id": "file",
  "string": "<a href=\"http:\/\/stackoverflow.com\/questions\/5335873\/how-to-get-html-from-json-data-using-mustache#xyz\">string</a>",
}}

MUSTACHE template:

{{#string}}
<div>
{{string}}
</div>
{{/string}}

Current Output:

<a href="https://stackoverflow.com/questions/5335873/how-to-get-html-from-json-data-using-mustache#xyz">string</a>

Output Needed:

string

Thanks you

like image 316
Chetan Sharma Avatar asked Mar 17 '11 07:03

Chetan Sharma


1 Answers

Current Output:

<a href="http://stackoverflow.com/questions/5335873/how-to-get-html-from-json-data-using-mustache#xyz">string</a>

That is not the output. What you actually get is something like

&lt;a href=&quot;http://stackoverflow.com/questions/5335873/how-to-get-html-from-json-data-using-mustache#xyz&quot;&gt;string&lt;/a&gt;

Which of course looks like what you've posted in a browser. Mustache HTML escapes all your variables by default, so they don't mess up your HTML.

In this case you don't want that, so you should use {{{string}}} in the template. Be sure to only do that with trusted variables, never use it to output any user input.

like image 50
svens Avatar answered Oct 17 '22 13:10

svens