Note that there are some explanatory texts on larger screens.

plurals
  1. POImproving a simple JavaScript templating technique
    primarykey
    data
    text
    <p>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. </p> <p>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.</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;!-- where templates will be injected into --&gt; &lt;div id="thumbContainer"&gt;&lt;/div&gt; &lt;!-- template used for thumbnails --&gt; &lt;div id="thumbTemplate" style="display:none"&gt; &lt;div class="thumb"&gt; &lt;div&gt;${caption}&lt;/div&gt; &lt;div&gt;${image}&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;script type="text/javascript"&gt; (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 '&lt;img src="test.png" /&gt;'; })() }); // Display on page by inserting into DOM document.getElementById('thumbContainer').appendChild(thumb); &lt;/script&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload