मैं जावास्क्रिप्ट में टेम्पलेट बनाने का एक आसान तरीका विकसित करने की कोशिश कर रहा हूं। मूल विचार यह है कि मुझे एक ऐसे पृष्ठ में HTML मिला है जो जावास्क्रिप्ट में किसी ऑब्जेक्ट के UI का प्रतिनिधित्व करता है, और उस HTML में चर जो जावास्क्रिप्ट ऑब्जेक्ट के गुणों के साथ प्रतिस्थापित होते हैं। एचटीएमएल प्रस्तुतियों को जावास्क्रिप्ट ऑब्जेक्ट्स को बाध्य करने के लिए तकनीक के रूप में सोचें।एक साधारण जावास्क्रिप्ट टेम्पलेटिंग तकनीक में सुधार
कोई आलोचना? क्या मुझे दस्तावेज़ खंडों का उपयोग किसी भी तरह से करना चाहिए? मैं अनिवार्य रूप से इस पर एक कोड समीक्षा की तलाश कर रहा हूँ। मैं किसी भी प्रतिक्रिया की सराहना करता हूं। (ध्यान दें कि यह ढांचा स्वतंत्र होना चाहिए।) यहां एक कामकाजी एक्समैपल है।
<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>
+1 // जादू – cherouvim
हाहा के लिए धन्यवाद, धन्यवाद! :) – JamesBrownIsDead