Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use custom templates in Backbone-forms?

There are few forms in my project which involve lot of validations and server calls. So, I thought of using 'backbone-forms.js' for these. Currently I am playing around with this code : http://jsfiddle.net/evilcelery/VkUFu/ to see if 'backbone-forms.js' caters to all my needs.

Surely we can give our own custom templates to individual components like 'list', 'date' etc as defined in https://github.com/powmedia/backbone-forms#customising-templates. But in my workplace, all html templates should be independent from the javascript implementations so that the classes and markup can be edited based on the needed appearances (javascript coding is based on the field ids which will not be altered). My problem is that I am unable to use my own custom template for the forms built using 'backbone-forms.js'.

Is there any way to make the template.html independent from javascript(like in case of handlebars.js) ?

Is there someway that we can use a compiled handlebars template with all form fields in the template.html and using Backbone.Form functionality or is this not possible?

Thanks.

like image 317
noob coder Avatar asked Oct 06 '22 22:10

noob coder


1 Answers

If I understand your question well, you would like to load html templates from individual sources dynamically (like from .../templates/category.html) instead of letting BackboneForms render it from the schema or having to define them in an ugly way in the javascript code like here

You can load your html template on the go as a string with ajax (or better, with Require.js) and call Backbone.Form.setTemplates({templateName: templateBodyAsString}). It won't override other already registered templates with other names, see setTemplates's implementation below.

If you use $.ajax(), you can put your form rendering code in the success callback. If you use Require.js, it will be easier, not to mention its caching mechanism, if all of your BB modules/forms load their own templates every time, then Require.js will only do the ajax request first time a module needs the same template.

The body of the Backbone.Form.setTemplates function:

function (templates, classNames) {
    var createTemplate = helpers.createTemplate;

    Form.templates = Form.templates || {};
    Form.classNames = Form.classNames || {};

    //Set templates, compiling them if necessary
    _.each(templates, function(template, key, index) {
      if (_.isString(template)) template = createTemplate(template);

      Form.templates[key] = template;
    });

    //Set class names
    _.extend(Form.classNames, classNames);
  } 
like image 151
Denes Papp Avatar answered Oct 10 '22 04:10

Denes Papp