spr*_*man 9 javascript jquery mustache
我第一次使用mustache.js.我发现的所有示例似乎都在谈论将所有内容放入内联,但我希望我的模板在外部文件中,以便它们可以在多个地方使用.我怎么做?(我的堆栈中有jQuery,如果这有所不同.)
所以说我有:
template.html
{{title}} spends {{calc}}
Run Code Online (Sandbox Code Playgroud)
data.js
var data = { title: "Joe", calc: function() { return 2 + 4; } };
Run Code Online (Sandbox Code Playgroud)
的index.html
<script type="text/javascript" src="data.js"></script>
<div id="target"></div>
<script type="text/javascript">
var template = ?????? // how do I attach the template?
var html = Mustache().to_html(template, data);
$('#target')[0].innerHTML = html;
</script>
Run Code Online (Sandbox Code Playgroud)
template = $('.template').val();
Run Code Online (Sandbox Code Playgroud)
你的模板在 DOM 中的位置...
<textarea class="template">
<h1>{{header}}</h1>
{{#bug}}
{{/bug}}
{{#items}}
{{#first}}
<li><strong>{{name}}</strong></li>
{{/first}}
{{#link}}
<li><a href="{{url}}">{{name}}</a></li>
{{/link}}
{{/items}}
{{#empty}}
<p>The list is empty.</p>
{{/empty}}
</textarea>
Run Code Online (Sandbox Code Playgroud)
您还可以将多个模板直接渲染到您的页面中......
<script id="yourTemplate" type="text/x-jquery-tmpl">
{{tmpl "#yourTemplate"}}
<div>Something: ${TemplateValue}</div>
</script>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4384 次 |
| 最近记录: |