[英]mustache.js is not working
我尝试使用 mustache.js 进行模板化,但我的基本代码不起作用 请帮助我出错的地方 -
var person = {
firstName: "Christophe",
lastName: "Coenraets"
};
var template = "<h1>{{firstName}} {{lastName}}</h1>";
var output = Mustache.render(template, person);
document.getElementById('result1').innerHTML = output;
上面的代码有效,但下面的代码无效:-
这一行写在我的 .html 页面中:
<script id="sample_template" type="text/template">
<h1>{{firstName}} {{lastName}}</h1>
</script>
这一行写在我的 .js 文件中:
var data ={
firstName: "Christophe",
lastName: "Coenraets"
};
var template = $('#sample_template').html();
//console.log(template); this prints the html content in console
var info = Mustache.to_html(template, data);
$('#result1').html(info);
我得到了解决方案,我有 mustache 服务器端和客户端,我上面描述的问题是,当我尝试在客户端填充占位符时,这些占位符已经在服务器端消耗了(因为我没有分散具有呈现服务器端和呈现客户端)。 所以他们在客户端渲染时没有占位符,所以只有我得到了 html 标签才会显示。
从文档中,似乎不推荐使用.to_html()
......
我和level_0有同样的问题。 服务器端的 Django 模板也使用与 mustache-js 相同的标签,即 {{ }}
这是一个简单的例子,它解决了 Django 服务器端模板问题。
<!DOCTYPE HTML>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.3.0/mustache.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
</head>
<body>
<div id="target">Loading...</div>
<script id="template" type="x-tmpl-mustache">
Hello {% templatetag openvariable %} name {% templatetag closevariable %}
</script>
<script>
$(document).ready(function() {
var template = $('#template').html();
console.log(template);
Mustache.parse(template); // optional, speeds up future uses
var rendered = Mustache.render(template, { name: "Luke" });
$('#target').html(rendered);
});
</script>
</body>
</html>
如果你像我一样在这个线程中结束,因为你在谷歌上搜索了“Mustache.to_html 不是一个函数”,你可以简单地用Mustache.to_html
替换Mustache.render
。 第一个已被删除,因此您可能更新了库。
这对我有用: http : //jsfiddle.net/evildonald/qK5NT/
js:
$(document).ready(function () {
var data ={
firstName: "Christophe",
lastName: "Coenraets"
};
var template = $('#sample_template').html();
var info = Mustache.to_html(template, data);
$('#result1').html(info);
});
html:
<script id="sample_template" type="text/template">
<h1>{{firstName}} {{lastName}}</h1>
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.