如何使用 MUSTACHE 从 JSON 数据获取 HTML?
我在新网站中使用 JSON 和 MUSTACHE 作为模板。但我不知道如何从 json 数据中获取 HTML。我在后端使用 PHP,它作为 API 提供者。我对这个概念很陌生。欢迎任何帮助和建议。
谢谢。
我正在使用的代码::
<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 数据就像::
{"menu": {
"id": "file",
"string": "<a href=\"http:\/\/stackoverflow.com\/questions\/5335873\/how-to-get-html-from-json-data-using-mustache#xyz\">string</a>",
}}
MUSTACHE 模板:
{{#string}}
<div>
{{string}}
</div>
{{/string}}
当前输出:
<a href="https://stackoverflow.com/questions/5335873/how-to-get-html-from-json-data-using-mustache#xyz">string</a>
需要输出:
谢谢
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:
Thanks you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这不是输出。您实际得到的是类似的内容
,当然看起来就像您在浏览器中发布的内容。 Mustache HTML 默认转义所有变量,因此它们不会弄乱您的 HTML。
在这种情况下,您不希望出现这种情况,因此您应该在模板中使用
{{{string}}}
。确保仅使用受信任的变量执行此操作,切勿使用它来输出任何用户输入。That is not the output. What you actually get is something like
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.看看 PHP 中的 json_decode ,这会给你一个数据数组(我假设) 可以提供给您的模板引擎:
Take a look at json_decode in PHP, that'll get you an array of your data which you (i presume) can feed to your templating engine: