Search code examples
templatesbackbone.jshandlebars.js

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?


Solution

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