Is it possible to include a template within a template? Maybe something similar to the way ERB handles partials?
Rather than attempting to render nested models in a fashion like ERB, it's better to let Backbone.js take care of this.
Note, I am using coffeescript syntax:
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
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() ))
so, in the end we have nested templates like this:
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>"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With