我正在尝试开发一种在JavaScript中创建模板的简单方法。基本的想法是,我在代表JavaScript中对象的UI的页面中获得了HTML,并且该HTML中的变量被JavaScript对象的属性替代。把它看作是将JavaScript对象绑定到HTML演示文稿的技巧。改进一个简单的JavaScript模板技术
任何批评?我应该以某种方式使用文档片段吗?我基本上是在寻找一个代码审查这一个。我会很感激任何反馈。 (请注意,这应该是独立于框架的。)这是一个工作示例。
<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 2010-02-14 06:27:44
哈哈,谢谢! :) – JamesBrownIsDead 2010-02-14 06:28:55