Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js with Eco Templates: How to include template within a template?

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:

  • Projects Index
    • Project
      • Session
      • Session
      • Session
      • Session
    • Project
      • Session
    • Project
      • Session
      • Session
like image 771
miketucker Avatar asked Oct 11 '22 00:10

miketucker


1 Answers

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>"
like image 115
twetzel Avatar answered Oct 17 '22 22:10

twetzel