How to render dust template with backbone

坚强是说给别人听的谎言 提交于 2019-12-24 14:45:25

问题


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.


回答1:


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);
});



回答2:


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
  )
  @


来源:https://stackoverflow.com/questions/12758506/how-to-render-dust-template-with-backbone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!