2012-06-05 78 views
1

我正在使用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> 

... 

然后我把这个文件作为一个部分包含在服务器端。

这有以下缺点:

  1. 模板一堆被塞进HTML文件。
  2. 找到给定的模板是很乏味的。

我正在寻找更好的方式来组织我的模板。我希望每个模板都能在自己的文件中生存。例如:

/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/views/my_controller/my_action /还包含/public/views/shared/my_shared_template.html。

我的问题:有没有提供这种或类似功能的库?或者,有没有人有其他组织建议?

回答

2

我使用了一个模板加载器,它在第一次需要时使用ajax加载模板,并将其缓存到本地以备将来的请求使用。我也使用debug变量,以确保当我在发展中的模板是不缓存:

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 
}) 
4

RequireJS是真正为AMD风格的依赖好的库管理。您实际上可以使用requireJS的'text'插件将模板文件加载到您的UI组件中。一旦模板附加到DOM,您可以使用任何MVVM,MVC库进行绑定,或者仅为您的逻辑使用jQuery事件。

我是BoilerplateJS的作者。 BoilerplateJS参考架构使用requireJS进行依赖管理。它还提供了一个参考实现来展示如何创建一个自包含的UI组件。自包含的意义来处理自己的视图模板,后面的代码,CSS,本地化文件等

Files in a BoilerplateJS UI Component

上有boilerplateJS主页提供一些更多的信息,在“UI组件”。

http://boilerplatejs.org/