Skip to content

Instantly share code, notes, and snippets.

@feload
Last active July 24, 2017 18:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save feload/80fd2cec6de2b9ba2034 to your computer and use it in GitHub Desktop.
Save feload/80fd2cec6de2b9ba2034 to your computer and use it in GitHub Desktop.
Basic templating function.
/**
* t().
* Converts a template into text by replacing placeholders based on an object properties.
*
* @param String template.
* @param Object params.
*
* @return String.
*/
const t = (template, params) => {
const phRegExp = new RegExp(/{([ ])?([a-zA-Z._-]+)([ ])?}/g);
const varRegExp = new RegExp(/[a-zA-Z._-]+/);
let text = template;
template.match(phRegExp).map(placeholder => {
const placeholders = placeholder.match(varRegExp)[0].split('.');
let tmp_value = params;
placeholders.map(prop => {
if(typeof tmp_value[prop] != 'object'){
text = text.replace(new RegExp(placeholder, 'g'), tmp_value[prop]);
}else{
if(tmp_value[prop].hasOwnProperty('length')){
text = text.replace(new RegExp(placeholder, 'g'), tmp_value[prop].join(''));
}else{
tmp_value = tmp_value[prop];
}
}
});
});
return text;
}
//------ Test data ---------//
let template = "My name is {name}, and my id is {id}; {nested.property} and {even.more.nested}. Do you know my id? -Yeah, it's {id}; Array? {prop_w_number}";
const params = {
id: 1,
name: 'Felipe',
nested: {
property: 'I talk to computers'
},
even: {
more: {
nested: 'I really enjoy programming JS applications.'
}
},
prop_w_number: [1,3,4,5]
};
console.log(t(template, params));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment