Search code examples
javascriptamdtemplatinghandlebars.js

Templating in a Javascript-Only Application


I will be developing a large, AMD-based javascript application, structured with backbone.js and potentially require.js. I am doing research on the best way to go, and one thing I would like to get into using is a template library, particularly handlebars.js.

My problem here is that I want to make javascript-only modules that can be loaded and implemented on the fly, well after the application is loaded. Templates are based on HTML tags, but I don't want to include html pages after the fact.

My question is: Is it stupid, or valid practice to mock up HTML templates as strings in your javascript, and then render them? I feel like it would kill the entire point in performance alone, but I really don't know.

This is an example of what I am talking about:

var render = function(html, model) {
  var tmpl = Handlebars.compile(html);
  return tmpl(model);
}

$(document).ready(function() {

  var template = '<div class="entry">' + 
                   '<h1>{{title}}</h1>' + 
                   '<div class="body">{{body}}</div>' + 
                 '</div>';

  var model = {
    title: 'I love templating,',
    body: 'And so do you!'
  }

  template = render(template, model);
  $(document.body).append(template);

});

Is this terrible practice, or is there a better way to implement this in a javascript-only application?


Solution

  • Template are used to separate html from javascript code. I suggest you to look at requireJS text plugin to load your template code in an AMD environment.