Eva*_*van 8 javascript jquery json github mustache
我刚开始使用Mustache,到目前为止我喜欢它,但这让我感到困惑.
我正在使用GitHub gist API来提取我的要点,我想要做的部分工作是将嵌入功能包含在我的页面中.问题是Mustache似乎不想与我的动态脚本标签有任何关系.
例如,这工作正常:
<div class="gist-detail">
{{id}} <!-- This produces a valid Gist ID -->
</div>
Run Code Online (Sandbox Code Playgroud)
此外,这很完美:
<div class="gist-detail">
<script src='http://gist.github.com/1.js'></script> <!-- Produces the correct embed markup with Gist ID #1 -->
</div>
Run Code Online (Sandbox Code Playgroud)
如果我试图将它们结合在一起,那就会出现严重错误:
<div class="gist-detail">
<script src='http://gist.github.com/{{id}}.js'></script> <!-- Blows up! -->
</div>
Run Code Online (Sandbox Code Playgroud)
Chrome Inspector会显示以下内容:
GET https://gist.github.com/%7B%7Bid%7D%7D.js 404 (Not Found)
Run Code Online (Sandbox Code Playgroud)
...看起来像我的东西是逃避或诸如此类的奇怪,所以我切换到原始语法:
<div class="gist-detail">
<script src='http://gist.github.com/{{{id}}}.js'></script> <!-- Blows again! -->
</div>
Run Code Online (Sandbox Code Playgroud)
我在Inspector中得到了相同的结果:
GET https://gist.github.com/%7B%7B%7Bid%7D%7D%7D.js 404 (Not Found)
Run Code Online (Sandbox Code Playgroud)
如何获取嵌入脚本标记的正确值?
编辑
我按如下方式注入模板(在document.ready:
function LoadGists() {
var gistApi = "https://api.github.com/users/<myuser>/gists";
$.getJSON(gistApi, function (data) {
var html, template;
template = $('#mustache_gist').html();
html = Mustache.to_html(template, {gists: data}).replace(/^\s*/mg, '');
$('.gist').html(html);
});
}
Run Code Online (Sandbox Code Playgroud)
实际模板是在ruby部分内部,但是它包含在div中(不是脚本标记,这是一个问题?)(隐藏):
<div id="mustache_gist" style="display: none;">
{{#gists}}
<!-- see above -->
{{/gists}}
</div>
Run Code Online (Sandbox Code Playgroud)
我认为一个div是好的而不是一个script因为在任何一种情况下,我都拉着.html().这是一个不好的假设吗?
您的模板似乎是 HTML 格式,并尝试使用以下命令检索模板html()要返回的 URL 转义前模板中的结果来检索模板。尝试将模板放在<script type="text/html">标签内。
当您将模板嵌入到除更多 HTML 元素作为子元素之外的 HTML 元素中时,浏览器可能会将其作为 HTML 进行处理。可能会发生逃逸。通过使用<script>非脚本内容类型的标签,您基本上是在告诉浏览器不要触摸您的模板。
| 归档时间: |
|
| 查看次数: |
7543 次 |
| 最近记录: |