Dynamic Handlebar Templates

Attempting to make templates more flexible by allowing the application of disparate data models and properties.

by Aubrey Taylor

HTML

<script src="http://cloud.github.com/downloads/wycats/handlebars.js/handlebars-1.0.0.beta.4.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script type="text/x-handlebars" id="template">
  <p>{{ get "primaryText" }}</p>
  <p>{{ get "secondaryText" }}</p>
</script>

<div>
  <h1>Uses exact same Handlebars template but different models / properties</h1>
  <hr>
</div>

<div id="container1"></div>
<hr>
<div id="container2"></div>

CSS

body {
  padding: 10px;
}

JavaScript

(function() {

  Handlebars.registerHelper("get", function(key, defaultValue) {
   	templateKeyMap = this["templateKeyMap"];
    return this[templateKeyMap[key]] || defaultValue;
  });

})();

var context = {
  title: "Title",
  description: "Description",

  templateKeyMap: {
    primaryText: "title",
    secondaryText: "description"
  }
};

var context2 = {
  title: "Second Title",
  pubDate: "January 01, 1979",

  templateKeyMap: {
    primaryText: "title",
    secondaryText: "pubDate"
  }
};

var template = Handlebars.compile($("#template").text());
var html = template(context);
var html2 = template(context2);

$("#container1").html(html);
$("#container2").html(html2);