ASem
ASem

Reputation: 142

Is there any way to render Handlebars templates on server via Backbone in front-end?

edited

This question is in addition to previous Handlebars with Backbone template not rendering problem in which browseser was not rendering forms at all now the problem was solved for the form but returns another error which is possibly also with the rendering.


I have an app with Backbone on front-end and Express in back-end with express-handlebars templates and I was trying to change from Underscore templating to Handlebars while still leaving backbone logic behind. So the way I did it - installing handlebars via Bower and then required it.

  app.ContactView = Backbone.View.extend({
     //....
    template: Handlebars.compile( $('#tmpl-contact').html() ),
     //....
  });

instead of

  app.ContactView = Backbone.View.extend({
     //....
    template: _.template( $('#tmpl-contact').html() ),
     //....
  });

But it returns errors and I don't really get what causes them.

When I try to load a page, for example:

http://192.168.33.10:3000/contact/

It doesn't shows any errors in the browser. But if I move to:

http://192.168.33.10:3000/about

which doesn't even have Backbone logic behind it returns an error:

You must pass a string or Handlebars AST to Handlebars.compile. You passed undefined

Which means that template is compiled before the DOM loads on the page. But my Backbone script is loading after html script e. g. after the {{{body}}} element. Also if there is a problem with an order I should get this error on every, not only when moving to another.

So I think the cause is some kind of a conflict between front-end handlebars and express-handlebars on a server. How to solve this, preferably that templates to be rendered via expHbs instance?

Upvotes: 0

Views: 563

Answers (2)

ASem
ASem

Reputation: 142

Problem solved by loading each Backbone part as a separate file for its route.

Upvotes: 0

machineghost
machineghost

Reputation: 35750

If the only change that you made was:

template: Handlebars.compile( $('#tmpl-contact').html() ),

to:

template: _.template( $('#tmpl-contact').html() ),

it wouldn't cause the problems you're describing. As the error message told you "You passed undefined", and undefined wouldn't have worked with the Underscore code either.

It seems more likely that you changed something else, and that change caused the issue you described. However, without more code (ideally a JS Fiddle) it's hard to say what.

Upvotes: 0

Related Questions