带有生态模板的 Backbone.js:如何在模板中包含模板? [英] Backbone.js with Eco Templates: How to include template within a template?

查看:14
本文介绍了带有生态模板的 Backbone.js:如何在模板中包含模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to include a template within a template? Maybe something similar to the way ERB handles partials?

与其尝试以 ERB 之类的方式渲染嵌套模型,不如让 Backbone.js 来处理.

Rather than attempting to render nested models in a fashion like ERB, it's better to let Backbone.js take care of this.

注意,我使用的是 coffeescript 语法:

Note, I am using coffeescript syntax:

Projects.IndexView

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()

模型项目有一个称为会话的嵌套集合:

the model Project has a nested collection called sessions:

Projects.ProjectView

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

ProjectSessions.ShowView

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

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

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

so, in the end we have nested templates like this:

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

      推荐答案

      这里有一个小帮手我用在spine上:

      here a little helper I use for spine:

      # 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>"
      

      这篇关于带有生态模板的 Backbone.js:如何在模板中包含模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆