Zac Gross

Code & More

Checking Nested Models in Backbone Forms

| Comments

When defining custom form templates in backbone forms you may want to conditionally include content based on whether or not the form is nested. The following code will allow you to check using the template markup:

1
2
3
4
5
<% if(this.options.fieldTemplate != "nestedField") { %>
  //form is nested inside another
<% } else { %>
  //form is not nested
<% } %>

This check will enable you to write fewer, more reusable form templates. The following changes to the default bootstrap template included with backbone forms allows you to include form submit and cancel buttons by setting a template data flag.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Form.template = _.template('\
    <div>\
    <form class="form-horizontal" data-fieldsets>\
    </form>\
    <% if(submitbtn && this.options.fieldTemplate != "nestedField") { %>\
      <button class="btn btn-primary createBtn" >Create</button>\
      <button class="btn btn-danger cancelBtn" >Cancel</button>\
    <% } %>\
    </div>\
  ');

//Setting the submitbtn flag in the templateData
//paramater will cause the buttons to appear on the form

var ExampleForm = Backbone.Form.extend({
      templateData: { submitbtn: true },
     });

Comments