Skip to content

Instantly share code, notes, and snippets.

@proddi
Last active November 19, 2023 16:26
Show Gist options
  • Save proddi/1aa0ba33e7448a20f855012d714df6e3 to your computer and use it in GitHub Desktop.
Save proddi/1aa0ba33e7448a20f855012d714df6e3 to your computer and use it in GitHub Desktop.
A html template engine in vanilla javascript.
<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>
/*
* 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