[英]How to define mustache partials in HTML?
这是我的HTML:
<script type="text/html" id="ul-template">
<ul id="list">
{{> li-templ}}
</ul>
</script>
<script type="text/html" id="ul-template2">
<div id="list2">
{{> li-templ}}
</div>
</script>
<script type="text/html" id="li-templ">
<p>{{ name }}</p>
</script>
正如你所看到的,我想重用#li-templ
部分,但似乎我必须将它写入一个名为li-templ.mustache
的文件然后我可以将它包含为partial
?
我可以在单个html文件中定义它们吗?
我假设你正在使用Mustache的JS风格。
在mustache.js中,partials的对象可以作为第三个参数传递给Mustache.render。 该对象应该由partial的名称键入,其值应该是部分文本。
你需要:
这里有一些jQuery就是这样做的:
var view = {"name" : "You"},
li = $('#li-templ').html(),
partials = {"li-templ": li},
ul1 = Mustache.to_html($('#ul-template').html(), view, partials),
ul2 = Mustache.to_html($('#ul-template2').html(), view, partials);;
document.write(ul1, ul2);
这是一个jsFiddle的所有工作 - http://jsfiddle.net/maxbeatty/EYDfP/
ICanHaz.js (ICH)可以帮助您解决这个问题。
ICanHaz.js :使用Mustache.js进行客户端模板化的简单/强大方法。
我发现混合模板(在脚本标签中)与页面中的普通HTML混淆了我的代码编辑器(语法高亮,缩进等)。 将它们作为单独的服务器加载可以保持HTML清洁。
查看此ICH pull请求,从服务器自动加载<script type="text/html" src="my-templates.html"></script>
到每个文件一个模板。
您还可以使用以下简单代码为每个远程HTML文件加载多个模板 :
function getTemplates(url) {
$.get(url, function (response) {
$('template', response).each(function () {
ich.addTemplate(this.id, $(this).text());
});
});
}
或者,如果您希望ICH从页面中的网址自动加载它们:
<head>
<link rel="templates" type="text/html" href="my-templates.html">
</head>
$("link[type=templates]").each(function (index, link) {
getTemplates(link.attr("href"));
});
在你的my-templates.html
<templates>
<template id="ul-template">
<ul id="list">
{{> li-templ}}
</ul>
</template>
<template id="ul-template2">
<div id="list2">
{{> li-templ}}
</div>
</template>
<template id="li-templ">
<p>{{ name }}</p>
</template>
</templates>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.