Last active
January 31, 2018 15:53
-
-
Save cesarfrick/1732534694fe77159b98dcbd1d1fe457 to your computer and use it in GitHub Desktop.
Simple template rendering (ES6)
This file contains hidden or 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
| /** | |
| * @method fromTemplate | |
| * @description | |
| * Converts an HTML element string to a DOM object | |
| * @param {String} templateString String representation of a DOM element (e.g. '<div>content</div>') | |
| * @returns {Node} | |
| */ | |
| export const fromTemplate = templateString => { | |
| var el = document.createElement('div'); | |
| el.innerHTML = templateString; | |
| return el.firstChild; | |
| } | |
| /** | |
| * @method prerender | |
| * @description | |
| * Mixes a template String with the given data and returns the resulting String | |
| * The template String has the required markup and the dynamic elements are represented in the way of {{element}} | |
| * @param {String} template The String representation of a DOM element | |
| * @param {Object} data An Object containing the data to fill the template | |
| * @return {String} An String representation of a DOM element with the data passed replacing the correspondant variables | |
| */ | |
| export const prerender = (template, data) => ( | |
| return Object.keys(data).reduce((prev, item) => { | |
| const regex = new RegExp(`{{${item}}}`, 'g'); | |
| return prev.replace(regex, data[item] || ''); | |
| }, template.trim()); | |
| ) | |
| /** | |
| * @method renderTemplate | |
| * @description | |
| * Combines prerender and fromTemplate functions to return a new HTML node with the provided data | |
| * @param {String} templateString A String representation of an HTML node with optional variable names | |
| * @param {Object} data An Object with the variables that will be replaced in the templateString | |
| * @return {HTMLNode} The rendered template as an HTML node. | |
| */ | |
| export const renderTemplate = (templateString, data) => fromTemplate(prerender(templateString, data)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment