Javascript 小胡子,使用外部模板
我正在阅读有关使用Mustache.js制作模板的内容。我不明白的是如何把模板放在哪里。我不想把它们放在同一个文件里Javascript 小胡子,使用外部模板,javascript,jquery,mustache,Javascript,Jquery,Mustache,我正在阅读有关使用Mustache.js制作模板的内容。我不明白的是如何把模板放在哪里。我不想把它们放在同一个文件里 $.get('test.htm', function(templates) { // Fetch the <script /> block from the loaded external // template file which contains our greetings template. var template = $(templ
$.get('test.htm', function(templates) {
// Fetch the <script /> block from the loaded external
// template file which contains our greetings template.
var template = $(templates).filter('#tpl-greeting').html();
$('body').append(Mustache.render(template, templateData));
});
//test.htm
<script id="tpl-greeting" type="text/html">
<dl>
<dt>Name</dt>
<dd>{{name}}</dd>
<dt>Time</dt>
<dd>{{timeNow}}</dd>
</dl>
</script>
$.get('test.htm',函数(模板){
//从加载的外部文件中获取块
//模板文件,其中包含我们的问候语模板。
var template=$(templates.filter('#tpl greeting').html();
$('body').append(Mustache.render(template,templateData));
});
//test.htm
名称
{{name}}
时间
{{timeNow}}
我必须创建一个返回模板的控制器,还是可以引用它 有几种方法可以做到这一点
.mst
(扩展名可以是您实际需要的任何内容)文件中即可。例如
var\u templateName=代码>。因此,当JS实际呈现时,它将与标记一起呈现,但代码仍然是可维护的。此外,通过这种方法,如果您使用的是CDN,那么缓存的JS将使您的站点受益匪浅
$.get
,$.getJSON
等方法加载外部HTML文件。更详细的实现是您可以像对待CSS和JS一样将模板放在单独的文件中。您可以使用从以下文件加载外部模板: 在模板中添加指向模板文件的链接:
<link href="path/to/template.mustache" rel="template" id="templateName"/>
雪佛龙的文档将给出更多使用fetch而非jQuery的2018备选方案示例:
fetch('template.mst')
.then(response => response.text())
.then(template => {
Mustache.parse(template);
var output = Mustache.render(template, data);
return document.getElementById('target').innerHTML = output;
}).catch(error => console.log('Unable to get the template: ', error.message));
谢谢你的回答,但是我不明白。为什么不让控制器返回一个“填充的”html并执行$(“#old”).replacetwith(“#new”)@用户874774您绝对可以。但是您仍然需要构造新的HTML和新的数据值,以便在replaceWith方法中使用。模板为您做到这一点,再加上使用模板允许统一性和清洁度。
fetch('template.mst')
.then(response => response.text())
.then(template => {
Mustache.parse(template);
var output = Mustache.render(template, data);
return document.getElementById('target').innerHTML = output;
}).catch(error => console.log('Unable to get the template: ', error.message));