Skip to content

Instantly share code, notes, and snippets.

@cxmeel
Created April 2, 2020 22:50
Show Gist options
  • Save cxmeel/84b0132bf1608ca7acbe5bbca86a7c63 to your computer and use it in GitHub Desktop.
Save cxmeel/84b0132bf1608ca7acbe5bbca86a7c63 to your computer and use it in GitHub Desktop.
Like a basic version of Handlebars/Mustache.

Setup

import StringTemplater from "path/to/StringTemplater.module.js";

const stringsToMap = {
  "year": new Date().getFullYear()
};

const stringTemplater = new StringTemplater(stringsToMap);
stringTemplater.apply();
<body>
  <span :str>&copy;{{year}} - ClockworkSquirrel</span>
</body>

Produces the following output: ©2020 - ClockworkSquirrel

export default class {
constructor(strings = {}, match = "*[\\:str]") {
this.strings = strings;
this.match = match;
}
apply = () => {
const templaterElements = document.querySelectorAll(this.match);
Array.from(templaterElements).forEach(element => {
Object.entries(this.strings).forEach(([key, value]) => {
element.outerHTML = element.outerHTML.replace(`{{${key}}}`, value);
});
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment