我正在使用Handlebars.js,目前我的所有模板都位于脚本标记中,这些脚本标记存在于包含数十个其他模板的.html文件中,也存在于脚本标记中。
<script type="text/template" id="template-1">
<div>{{variable}}</div>
</script>
<script type="text/template" id="template-2">
<div>{{variable}}</div>
</script>
<script type="text/template" id="template-3">
<div>{{variable}}</div>
</script>
...然后,我将服务器端的这个文件作为部分文件。
这有以下缺点:
我正在寻找一种更好的方法来组织我的模板。我希望每个模板都保存在自己的文件中。例如:
/public/views/my_controller/my_action/some_template.html
/public/views/my_controller/my_action/some_other_template.html
/public/views/my_controller/my_other_action/another_template.html
/public/views/my_controller/my_other_action/yet_another_template.html
/public/views/shared/my_shared_template.html然后在我的视图顶部,在后端代码中,当页面加载时,我可以包括这些模板,如下所示:
SomeTemplateLibrary.require(
"/public/views/my_controller/my_action/*",
"/public/views/shared/my_shared_template.html"
)这将包括/public/view/my_controller/my_action/中的所有模板,还包括/public/view/shared/my_shared_template.html。
我的问题:是否有任何库提供这种或类似的功能?或者,有没有人有其他的组织建议?
发布于 2012-08-17 09:56:58
RequireJS确实是一个很好的库,用于管理AMD风格的依赖关系。实际上,您可以使用requireJS的“text”插件将模板文件加载到UI组件中。一旦模板附加到DOM,您可以使用任何MVVM、MVC库进行绑定,或者只对逻辑使用jQuery事件。
我是BoilerplateJS的作者。BoilerplateJS参考体系结构使用requireJS进行依赖关系管理。它还提供了一个参考实现来展示应该如何创建一个自包含的UI组件。自包含在意义上处理自己的视图模板,代码背后,css,本地化文件等。

在boilerplateJS主页"UI组件“下还有更多的信息可用。
http://boilerplatejs.org/
发布于 2012-07-17 22:51:01
我使用一个模板加载器,在第一次需要时使用ajax加载模板,并在本地缓存它以供将来的请求使用。我还使用一个调试变量来确保在开发过程中没有缓存模板:
var template_loader = {
templates_cache : {},
load_template : function load_template (params, callback) {
var template;
if (this.templates_cache[params.url]){
callback(this.templates_cache[params.url]);
}
else{
if (debug){
params.url = params.url + '?t=' + new Date().getTime(), //add timestamp for dev (avoid caching)
console.log('avoid caching url in template loader...');
}
$.ajax({
url: params.url,
success: function(data) {
template = Handlebars.compile(data);
if (params.cache){
this.templates_cache[params.url] = template;
}
callback(template);
}
});
}
}
};模板的加载方式如下:
template_loader.load_template({url: '/templates/mytemplate.handlebars'}, function (template){
var template_data = {}; //get your data
$('#holder').html(template(template_data)); //render
})发布于 2013-03-27 07:31:02
我为这个目的编写了一个方便的jquery插件。
https://stackoverflow.com/questions/10902691
复制相似问题