带有Eco模板的Backbone.js:如何在模板中包含模板?

mik*_*ker 5 templates ruby-on-rails coffeescript backbone.js

是否可以在模板中包含模板?也许类似于ERB处理部分的方式?

而不是尝试以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()
Run Code Online (Sandbox Code Playgroud)

模型Project有一个名为sessions的嵌套集合:

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)
Run Code Online (Sandbox Code Playgroud)

ProjectSessions.ShowView

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

render: ->
    $(this.el).html(@template(@model.toJSON() ))
Run Code Online (Sandbox Code Playgroud)

所以,最后我们有这样的嵌套模板:

  • 项目索引
    • 项目
      • 会议
      • 会议
      • 会议
      • 会议
    • 项目
      • 会议
    • 项目
      • 会议
      • 会议

小智 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>"
Run Code Online (Sandbox Code Playgroud)


Sim*_*tti -1

如果为模板添加前缀.erb,则可以使用 ERB 处理器。

更改yourfile.js.coffeeyourfile.js.coffee.erb,然后您就可以将<%= %>标签添加到您的 CoffeeScript 模板中。