1
votes

I'm trying to display a dust template (compiled) within a backbone view.

here is my render function in the view :

render: ->
  dust.render("customer-item", @model.toJSON(), (err, output) ->
    throw err if err
    $(@el).html output
  )
  @

When i lead the view i see 2 divs added inside my container (corresponding to the 2 models that should be loaded) but they are both empty. The individual template is not redered... When I debug the "output" variable i see the template so in theory it should be loaded properly...

When I do a simple test I can see an output for :

render: ->
      $(@el).html "<span>TEST</span>"
      @

But for that scenario I have no output :

render: ->
      dust.render("customer-item", @model.toJSON(), (err, output) ->
        $(@el).html "<span>TEST</span>"
      )
      @

Many thanks for your help.

2

2 Answers

2
votes

I didn't used Dust that much but for what I remember you should compile your template first like that (in plain Javascript):

var source   = $("#some-template").html();
var compiled = dust.compile(source,"table"); 

dust.loadSource(compiled);

dust.render("table",this.model.toJSON(),function(err,out){
    $(el).html(out);
});

EDIT:

I think I found where the problem lies: when you call $(this.el).html(out) inside your dust.render function, this is out of context. So you have to change your render function to something like that:

var self = this;
dust.render("table",this.model.toJSON(),function(err,out){
    $(self.el).html(out);
});
1
votes

As @Ingro explained this is an issue the this (@) context.

An option is to assign the this to a local variable (like "self" or "that")

render: ->
  self = @
  dust.render("customer-item", @model.toJSON(), (err, output) ->
    throw err if err
    self.$el.html output
  )
  @

Another option is to use CoffeeScript's "=>" (fat arrow)

render: ->
  dust.render("customer-item", @model.toJSON(), (err, output) =>
    throw err if err
    @$el.html output
  )
  @