2011-09-13 140 views
5

是否可以在模板中包含模板?也許類似於ERB處理偏好的方式?Backbone.js與生態模板:如何在模板中包含模板?

與其試圖以像ERB這樣的方式呈現嵌套模型,最好讓Backbone.js處理此問題。

注意,我使用CoffeeScript的語法:

Projects.IndexView

template: JST["backbone/templates/projects/index"] 

addAll:() -> 
    @options.projects.each(@addOne) 

addOne: (project) -> 
    view = new Worktimer.Views.Projects.ProjectView({model : project}) 
    @$("#projects-table").append(view.render().el) 

render: -> 
    $(@el).html(@template(projects: @options.projects.toJSON())) 
    @addAll() 

模型項目已經嵌套集合稱爲會話:

Projects.ProjectView

template: JST["backbone/templates/projects/project"] 

$(@el).html(@template(@model.toJSON()))  
for s in @model.sessions.models 
    v = new Worktimer.Views.ProjectSessions.ShowView(model: s) 
    $(@el).find('.sessions').append(v.render().el) 

ProjectSessions.ShowView

template: JST["backbone/templates/project_sessions/show"] 

render: -> 
    $(this.el).html(@template(@model.toJSON())) 

所以,最終我們嵌套模板是這樣的:

  • 項目指標
    • 項目
      • 會議
      • 會議
      • 會議
      • 會議
    • 項目
      • 會議
    • 項目
      • 會議
      • 會議

回答

-1

如果以.erb作爲模板的前綴,則可以使用ERB處理器。

更改yourfile.js.coffeeyourfile.js.coffee.erb,然後您就可以將<%= %>標記添加到您的CoffeeScript模板。

+0

這將是內生態,所以你建議做file.jst.eco.erb? – miketucker

+0

您追加的擴展名越多,將使用的處理器就越多。 –

+0

另外,由於ECO和ERB都使用'<%= %>',ERB會在ECO達到它之前吞噬所有插值! :) – micapam

0

我不認爲生態支持這一點。它更像是一個簡單的模板系統,比如Mustache,而不是一個完整的ERB替代品。在Rails上,您可能會渲染一個Eco模板並將輸出注入ERB或Haml模板。

對於Node.js開發,您可能需要查看CoffeeKup,它允許您在CoffeeScript中執行模板並支持偏分量。

+0

謝謝,我用Backbone和Rails 3.1使用Eco。最終結合使用骨幹向父母注入個人模板。 – miketucker

5

這裏的小幫手我用脊柱:

# Render Partials in ECO-Templates like in Rails-ERB 
# 
# usefull to clean up structure in spine.js and other js-mvc´s like backbone 
# 
# usage: 
# <%- render_partial 'path/to/partial' %> .. will render ../spine-app/views/path/to/_partial.jst.eco 
# <%- render_partial 'path/to/partial', foo: 'bar' %> .. will render ../spine-app/views/path/to/_partial.jst.eco .. locals = @foo 
# 
window.render_partial = (path, options = {}) -> 
    # add the leading underscore (like rails-partials) 
    path = path.split('/') 
    path[ path.length - 1 ] = '_' + path[ path.length - 1 ] 
    path = path.join('/') 
    # render and return the partial if existing 
    try 
     JST["app/views/#{ path }"](options) 
    catch error 
     # if App.Environment != 'production' then "<p class='error'>Sorry, there is no partial named '#{ path }'.</p>" else '' 
     "<p class='error'>Sorry, there is no partial named '#{ path }'.</p>"