JavaScript'te şablon oluşturmanın basit bir yolunu geliştirmeye çalışıyorum. Temel fikir, JavaScript'te bir nesnenin UI'sini ve bu HTML'deki JavaScript nesnesinin özellikleriyle değiştirilen değişkenleri temsil eden bir sayfada HTML olduğudur. JavaScript nesnelerini HTML sunumlarına bağlamak için bir teknik olarak düşünün.Basit bir JavaScript şablonlama tekniğini geliştirme
Herhangi bir eleştiri var mı? Bir şekilde belge parçaları kullanmalı mıyım? Aslında bu konuda bir kod incelemesi arıyorum. Herhangi bir geri bildirim için teşekkür ederiz. (Bu çerçeveden bağımsız olması gerektiğini unutmayın.) İşte bir çalışma 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>
+1 for magic – cherouvim
Haha, teşekkürler! :) – JamesBrownIsDead