1
votes

Since a backbone form extends a backbone view, I guess that using a custom template sould be done the same way.

First : Insert a template as a script type="text/html" element in the header

<head>
    [ ... ]
    <script type="text/html" id="myTemplate">
        <h1>This is a template for my view</h1>
    </script>
</head>

Then set the view's template attribute using the id of the template

var myView= new Backbone.View.extend({
    template: '#myTemplate',
    [...]
});

For backbone form, the template doesn't work :

<head>
    [...]
    <script type="text/javascript" src="scripts/jquery.js"></script>
    <script type="text/javascript" src="scripts/underscore.js"></script>
    <script type="text/javascript" src="scripts/backbone.js"></script>
    <script type="text/javascript" src="scripts/backbone-forms.js"></script>
    <script type="text/html" id="myTemplate">
        <h2>This is my custom form template!</h2>
        <form><%= fieldsets %></form>
    </script>
</head>
<body>
    <div id="myform"></div>
    <script type="text/javascript">
        $(document).ready(function(){
            MyModel = Backbone.Model.extend({
                schema: {
                    id : {type : "Number", validators : ["required"]},
                    first_name: {type : "Text", validators : ["required"]},
                    last_name: {type : "Text", validators : ["required"]},
                    screen_name: {type : "Text"}
                }
            });
            var myModel = new MyModel();
            var myForm = new Backbone.Form({
                template: '#myTemplate',
                model : myModel
            });
            $('#myform').html(myForm.render().el);
        });
    </script>
</body>
</html>

This code outputs the following error :

Uncaught TypeError: Property 'template' of object [object Object] is not a function

Then I try using Underscore when setting the template attribute. It does not work either

var myForm = new Backbone.Form({
    template: _.template($('#myTemplate')),
    model : myModel
});

Also a get a different error with the above code :

Uncaught TypeError: Object [object Object] has no method 'replace' 

I'm new to backbone / backbone form. Someone could tell me what I do wrong?

Thanks!

1

1 Answers

1
votes

Try

template: function(attrs) { return _.template($('#myTemplate').html(), attrs)},

Use template like this:

$('body').append(this.template({fieldsets: 'fieldsets'}));

See a working example http://jsbin.com/uzutes/2/