3

I am using underscore.js templating and I am finding that I need logic in my templates to control their rendering. One example might be to ensure the state of a form is retained and rendered correctly across a template re-render.

Does anyone have any tips on how best to reduce the logic in my templates? Is this even a desireable goal?

Ben Aston
  • 45,997
  • 54
  • 176
  • 303
  • I have the same problem in my templates. Here is the question about why reducing logic is desirable: [link](http://stackoverflow.com/questions/3896730/whats-the-advantage-of-logic-less-template-such-as-mustache) – lanan Feb 09 '12 at 18:43

1 Answers1

0

I typically do this with Backbone which saves some effort but since it's not mentioned in your question here's a brief example of how I might use a logicless form template and mantain the values using only underscore and jQuery:

    var app = {}; //namespace
    app.formData = {};
    app.template = '<form id="form"><input type="text" id="first" value="<%= first %>" /><input type="text" id="second" value="<%= second %>" />';
    app.storeFormData = function() {
        if ($('#form').length) {
           $('#form input').each(function() {
           app.formData[$(this).attr('id')] = $(this).val();
           });
         } else { //initialize formData object for first render
        var form = $(app.template);
        form.find('input').each(function() {
            app.formData[$(this).attr('id')] = '';  
        });
         }
     };
    app.render = function() {
        console.log('rendering');
         app.storeFormData(); //stash current state of form before re-rendering
         $('#formDiv').html(_.template(app.template, app.formData));
         _.each(app.formData, function(val, id) {
           $('#'+id).val(val);
          });
     };

    setInterval(app.render, 5000);

This code will automatically redraw the form every 5 seconds, and stashes the form state in memory before doing so, with a completely logicless template. Very simplistic example, but hopefully it gives you some ideas to run with.

Brian Zeligson
  • 162
  • 2
  • 3