我只知道通过underscore.js定义模板的一种方法,它看起来像:
<script type="text/template" class="about">
<h1><%- about.title %></h1>
<p><%- about.content %></p>
</script>
<script type="text/template" class="work">
<h1><%- work.title %></h1>
<p><%- work.content %></p>
</script>
<script type="text/template" class="contact">
<h1><%- contact.title %></h1>
<p><%- contact.content %></p>
</script>
...
这样,为每个模板添加一个脚本标记到头部看起来很讨厌。我只想要一个外部文件来存储所有html模板,并在需要时加载文件的特定部分。
例如;我的文件是&#34; templates.file&#34;它包含所有模板:
<!-- About Template -->
<h1><%- about.title %></h1>
<p><%- about.content %></p>
<!-- Work Template -->
<h1><%- work.title %></h1>
<p><%- work.content %></p>
<!-- Contact Template -->
<h1><%- contact.title %></h1>
<p><%- contact.content %></p>
除了backbone.js和underscore.js之外,是否可以在不加载任何其他框架的情况下执行此操作?哪种语法适合这种文档?最重要的是,我如何加载和查看templates.file的一部分,例如只有联系部分?
答案 0 :(得分:2)
在尝试了许多可能性后,我写了一段我需要的代码。我必须回答我的问题,因为有人可能需要它。这是我如何在一个外部html文件中收集多个模板,然后在我需要时将它们加载到我的脚本文件中。
templates.html
<html>
<head>
</head>
<body>
<script type="html/template" id="about">
<h3><%= title %></h3>
</script>
<script type="html/template" id="contact">
<h3><%= title %></h3>
</script>
</body>
</html>
和我的剧本:
$.ajax({
url: "templates.html",
dataType: "html",
async: false,
success: function(data) {
// we have to use "filter" instead of "find", "find" is failing
// we can use underscore's unescape method for &, <, >, "
contactTemplate = _.unescape($(data).filter("#contact").html());
}
});
var AppView = Backbone.View.extend({
el: '#container',
template: _.template(contactTemplate),
initialize: function(){
this.render();
},
render: function(){
this.$el.html(this.template({title: 'Contact'}));
}
});
var appView = new AppView();