2012-06-05 65 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/