Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

View partials in BackboneJS

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?

like image 373
evilcelery Avatar asked Mar 22 '26 08:03

evilcelery


1 Answers

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:

%form#story_form.new_story{method: "post"}

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.

like image 164
mikong Avatar answered Mar 24 '26 22:03

mikong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!