backbone.jscoffeescriptjst

Dynamic JST template selection with backbone


I have a view that needs different templates for different models.

I'm implementing a payment provider configuration, and it requires a different set of options for different payment providers.

Here is what I have now in my view code:

robokassa: JST["payment_providers/robokassa"]
cash: JST["payment_providers/cash"]

render: =>
  template_name = @model.get('name')
  switch template_name
    when "robokassa" then $(@el).html(@robokassa(payment_provider: @model))
    when "cash" then $(@el).html(@cash(payment_provider: @model))        

It works, but it's ugly.

I tried something like this, but I can't find a definitive manual on how to use the JST object except for the simple use cases:

render: =>
  template_name = @model.get('name')
  $(@el).html(JST["payment_providers/#{template_name}"](payment_provider: @model)

This returns an error that says it's not a function.

I guess, ideally, the solution would look like

template: => 
  JST["payment_providers/#{@model.get('name')}"](payment_provider: @model)
...
render: =>
  $(@el).html(@template())

But I can't figure out how to correctly write it.

Update

The latter is indeed correct, the gotcha was that @model wasn't loaded when render was called.


Solution

  • You CoffeeScript syntax seems fine to me.

    The difference between your first (working) sample and the two others is, that in the first code sample the JST object is accessed when your class is evaluated, and in the two latter samples only when the view is rendered.

    Could the state of the JST object have changed in between so that the templates are no longer present at render time?