Include conditional logic in Handlebars templates, or just use javascript?
Asked Answered
V

1

1

I'm writing a javascript web app using Backbone and Marionette, and my templates are created using Handlebars.

I have a view with three sections: a progress indicator, results list, and footer. Each of these may be shown or hidden based on if an operation is in progress or if there was an error.

Should I include conditional code in the Handlebars template, along the lines of {{unless resultsFetched}} and do this.render() often, or use javascript in the view like this.ui.resultsList.show() and this.ui.resultsList.hide()?

Thanks.

Update

Here are what I think are some pros and cons to having logic in the view templates:

Pros:

  • I think this looks like a declarative (instead of imperative) style, where the view says that it'll act a certain way based on model state.
  • As things get more complex, it'd probably be easier to read a template that has conditional logic than javascript code where show() and hide() is used extensively.

Cons:

  • Is the MVC architecture still being obeyed?
  • This goes against Mustache's philosophy of logic-less views
Velour answered 3/7, 2013 at 17:33 Comment(0)
A
0

As a general rule, you'll want to keep as much logic in the Views as possible and only have presentation in your templates. That isn't always practical to be sure, but the larger your app gets, the cleaner you're going to want your templates to be.

That being said, today I used a for loop in an Underscore template because I had no need for a CollectionView-ItemView combo for the little things in the list that I was adding to the DOM.

TL:DR; Try to stick to my first paragraph, but use your instincts :)

Apulia answered 27/7, 2013 at 1:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.