I'm trying to develop a simple way of creating templates in JavaScript. The basic idea is that I've got HTML in a page that represents the UI of an object in JavaScript, and variables in that HTML that are replaced with properties of the JavaScript object. Think of it as technique for binding JavaScript objects to HTML presentations.
Any critiques? Should I be using document fragments somehow? I'm essentially looking for a code review on this one. I'd appreciate any feedback. (Note that this should be framework independent.) Here's a working exmaple.
<html>
<body>
<!-- where templates will be injected into -->
<div id="thumbContainer"></div>
<!-- template used for thumbnails -->
<div id="thumbTemplate" style="display:none">
<div class="thumb">
<div>${caption}</div>
<div>${image}</div>
</div>
</div>
</body>
<script type="text/javascript">
(function() {
// Cache the templates' markup in case that template is used again
var cache = [];
// Magic
document.templatized = function(templateId, properties) {
// Get the template from cache or get template and add to cache
var template = cache[templateId] || (function() {
cache[templateId] = document.getElementById(templateId).innerHTML;
return cache[templateId];
})();
// Create the DOM elements that represent the markup
var shell = document.createElement('div');
shell.innerHTML = template.replace(/\$\{(\w+)\}/g, function(match, key){
return properties[key] || match;
});
// Return those DOM elements
return shell.children[0].cloneNode(true);
};
})();
// Create DOM elements with values bound to thumbnail object
var thumb = document.templatized('thumbTemplate', {
caption: 'Summer',
image: (function() {
// More complicated logic that requires conditions here...
return '<img src="test.png" />';
})()
});
// Display on page by inserting into DOM
document.getElementById('thumbContainer').appendChild(thumb);
</script>