hawk / files / public / js / template.js
template.js
| 1 | /** |
| 2 | * Get a template from a string |
| 3 | * https://stackoverflow.com/a/41015840 |
| 4 | * @param {String} str The string to interpolate |
| 5 | * @param {Object} params The parameters |
| 6 | * @return {String} The interpolated string |
| 7 | */ |
| 8 | function interpolate(str, params) { |
| 9 | let names = Object.keys(params); |
| 10 | let vals = Object.values(params); |
| 11 | return new Function(...names, `return \`${str}\`;`)(...vals); |
| 12 | } |
| 13 | |
| 14 | function htmlToElement(html) { |
| 15 | var template = document.createElement('template'); |
| 16 | html = html.trim(); // Never return a text node of whitespace as the result |
| 17 | template.innerHTML = html; |
| 18 | return template.content.firstChild; |
| 19 | } |
| 20 | |
| 21 | function createTemplatedHtml(templateId, params) { |
| 22 | const template = document.querySelector(`#${templateId}`); |
| 23 | const html = interpolate(template.innerHTML, params); |
| 24 | return html; |
| 25 | } |