won*_*ng2 25 html javascript mustache
这是我的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>
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,我想重用这个#li-templ部分,但似乎我必须将它写入一个名为li-templ.mustachethen 的文件然后我可以将它包括在内partial?
我可以在单个html文件中定义它们吗?
max*_*tty 28
我假设你正在使用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);
Run Code Online (Sandbox Code Playgroud)
这是一个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());
});
});
}
Run Code Online (Sandbox Code Playgroud)
或者,如果您希望ICH从页面中的网址自动加载它们:
<head>
<link rel="templates" type="text/html" href="my-templates.html">
</head>
Run Code Online (Sandbox Code Playgroud)
$("link[type=templates]").each(function (index, link) {
getTemplates(link.attr("href"));
});
Run Code Online (Sandbox Code Playgroud)
在你的 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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20687 次 |
| 最近记录: |