使用Mustache.js嵌入原始JSON [英] Using Mustache.js to Embed Raw JSON
问题描述
我在命令行上使用小胡子,将JSON对象嵌入HTML对象内的<script>
标记内.
I am using mustache on the command line to embed a JSON object inside of <script>
tags within an HTML object.
cat sampleData.json | mustache - man_report.mustache > output.html
样本数据如下:
{"report_type":"total_by_age_group",
"data":[{"age_group":"Age 41 - 65","percent":41.04},
{"age_group":"Age Over 66","percent":19.11},
{"age_group":"Age < 18 Or Invalid Birth Date","percent":0.00},
{"age_group":"Age 18 - 25","percent":8.03},
{"age_group":"Age 26 - 40","percent":31.82}]}
在生成的HTML文件中我也希望看到什么.
Which is what I would like to also see in the resultant HTML file.
report.mustache看起来像:
report.mustache looks like:
reportObject = {{data}}
output.html看起来像这样:
output.html looks like this:
reportObject = [object Object],[object Object],[object Object],[object Object],[object Object]
我只想要与开始时完全相同的JSON.有什么想法吗?
I just want the exact same JSON as I started with. Any ideas?
推荐答案
有些古老,但这是我进行搜索时遇到的第一个问题.我在这里找到了答案: https://stackoverflow.com/a/15580946/1961413
A little bit old, but this was the first question that came up when I did a search. I found an answer here: https://stackoverflow.com/a/15580946/1961413
如果能够预处理数据,则可以将其字符串化.这将使它成为可以嵌入的字符串:
If you are able to preprocess the data, you could stringifiy it. This would make it a string that could be embedded:
var sampleData = JSON.stringify(sampleData);
完成此操作后,您需要确保Moustache不对字符串进行HTML化处理(将车把向上翻三倍):
Once you've done this you need to ensure that Mustache doesn't HTMLize the string (triple up the handlebars):
var reportObject = {{{.}}};
然后您可以在您的网页中访问它:
You can then access it in you webpage:
alert(reportObject.report_type);
for($data in reportObject.data){
alert(JSON.stringify(reportObject.data[$data]));
}
这篇关于使用Mustache.js嵌入原始JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!