Last active
November 19, 2023 16:26
-
-
Save proddi/1aa0ba33e7448a20f855012d714df6e3 to your computer and use it in GitHub Desktop.
A html template engine in vanilla javascript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<body> | |
<p template="hello"> | |
Hello <i>{name}</i> | |
</p> | |
<script> | |
var HelloTemplate = new Template(document.querySelector("[template=hello]")); | |
var clone = HelloTemplate.clone({ name: "John Doe" }).append(); | |
clone.update({ name: "John Update" }); | |
</script> | |
</body> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* A micro template engine in vanilla javascript | |
* example: https://jsfiddle.net/at2h6ob0/ | |
*/ | |
var Template = function(node) { | |
this.node = node; | |
this.parent = node.parentNode; | |
this.parent.removeChild(node); | |
this.html = node.innerHTML; | |
}; | |
Template.prototype.clone = function clone(scope) { | |
return new TemplateClone(this, scope || {}); | |
}; | |
var TemplateClone = function(template, scope) { | |
this.template = template; | |
this.scope = scope; | |
this.node = template.node.cloneNode(false); | |
this.update(); | |
}; | |
TemplateClone.prototype.update = function update(scope) { | |
scope = scope || this.scope; | |
this.node.innerHTML = this.template.html.replace(/\{\s*(\w+)\s*\}/g, function(all, key) { | |
var value = scope[key]; | |
return (value === undefined) ? "{" + key + "}" : value; | |
}); | |
}; | |
TemplateClone.prototype.append = function append() { | |
this.template.parent.appendChild(this.node); | |
return this; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment