我的骨干应用程序目前的模板内联HTML如下:
<body>
<div id="container">
<header></header>
<nav></nav>
<div id="pagecontent"></div>
<footer></footer>
</div>
<!-- Featured Articles/Homepage Template -->
<script type="text/template" id="featuredarticles">
<link rel="stylesheet" href="css/homepagecontent.css" />
<section id="banner"></section>
<aside>
<div></div>
<div></div>
</aside>
<section id="main"></section>
<section id="opinion">
<div></div>
<div></div>
<div></div>
</section>
<section id="travel">
<div></div>
<div></div>
<div></div>
</section>
</script>
<!-- Content Articles Template -->
<script type="text/template" id="contentarticles">
<link rel="stylesheet" href="css/categorypagecontent.css" />
<section id="main"></section>
<aside></aside>
</script>
<!-- Require.js reference -->
<script src="/js/libs/require.js" data-main="/js/app.js"></script>
</body>
我是否可以将HTML外部化。如果是这样,我将如何外化(即使用视图),如下所示:
<!-- Featured Articles/Homepage Template -->
<script type="text/template" id="featuredarticles">
<!-- HTML rendered externally -->
</script>
<!-- Content Articles Template -->
<script type="text/template" id="contentarticles">
<!-- HTML rendered externally -->
</script>
以下是我如何从视图中呈现模板的片段:
define(['underscore', 'backbone', 'collections/bannerCollection', 'collections/featuredArticlesCollection', ], function (_, Backbone, bannerCollection, featuredArticlesCollection) {
var featuredArticlesView = Backbone.View.extend({
el: $('#pagecontent'),
initialize: function () {
this.render();
},
render: function () {
var that = this;
var template = _.template($('#featuredarticles').html(), {});
that.$el.html(template);
return that;
}
});
return featuredArticlesView;
});
我一直在阅读有关偏见的内容,但需要一些有关最佳做法的指导,以及是否应该如何/如何分析内联HTML。
答案 0 :(得分:1)
我找回了这个模板管理员的小片段(不能记住作者,对不起):
TemplateManager = {
templates: {}, // holds the templates cache
get: function(id, callback){
var template = this.templates[id];
if (template) { // return the cached version if it exists
callback(template);
} else {
var that = this;
// fetch, cache and return the template
$.get(id + ".html", function(template) {
that.templates[id] = template;
callback(that.templates[id]);
});
}
}
};
它获取模板文件,缓存它并在加载后调用回调函数,如下所示:
TemplateManager.get('path/to/your/template', function(resp) {
// resp is the template markup
return this;
});
希望它有所帮助。
更新
这是一个工作小提琴: