是否可以在模板中包含模板?也许类似于 ERB 处理部分的方式?
与其尝试以 ERB 之类的方式渲染嵌套模型,不如让 Backbone.js 来处理这个问题。
注意,我使用的是 Coffeescript 语法:
项目.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()
模型项目有一个名为会话的嵌套集合:
项目.项目视图
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)
项目会话.ShowView
template: JST["backbone/templates/project_sessions/show"]
render: ->
$(this.el).html(@template(@model.toJSON() ))
所以,最后我们有这样的嵌套模板:
- Projects Index
- Project
- Session
- Session
- Session
- Session
- Project
- Project
这是我用于脊柱的小帮手:
# 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>"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)