Asked By: Anonymous
Are there any ways to use view partials in Backbone? I’m using the built in Underscore templating and there isn’t much documentation on this.
If not, are there any standards/conventions or suggested ways of doing this?
Answered By: Anonymous
Yes, I have tried this recently. Make sure to read on the Backbone documentation, particularly the View section.
For example, you have a _new.jst.haml:
Then, you can have a _form.jst.haml that contains the form elements. In your Backbone.View, you can first append the new template in your el, followed by using the view-scoped selectors of Backbone (this is in their official documentation, under “$(jQuery or Zepto)” section):
$(this.el).html(window.JST['stories/_new'](attrs)); ... this.$('#story_form').html(window.JST['stories/_form'](attrs));
I was using Rails and so I initially read up on using Backbone.js with Rails from this article. There’s a link to a part 2 at the end of that article. I suggest you skip the part in the first article where he uses string concatenation for updating the views. Also, my approach now is quite different from how he did it, but I think it’s a pretty good starting point, and I don’t have my own article to show for anyway.
My code examples are somewhat short, but I guess I don’t want to write an entire tutorial here. Just let me know what doesn’t work, and what step you think is missing and I’ll update the answer.