Skip to content

Instantly share code, notes, and snippets.

@im4aLL
Created April 26, 2024 04:34
Show Gist options
  • Save im4aLL/6893b9a051135c0289cf558097025802 to your computer and use it in GitHub Desktop.
Save im4aLL/6893b9a051135c0289cf558097025802 to your computer and use it in GitHub Desktop.
Nano template engine
/**
* Parse template string
*
* @usage parseTemplate(`my name is {name} {nested.name}`, {name: 'foo', nested: { name: 'bar' }})
* @param template string
* @param data object
* @returns string
*/
export function HelperParseTemplate(template: string, data: any): string {
return template.replace(/\{([\w\\.]*)\}/g, (str: string, key: string) => {
const keys = key.split('.');
let v = data[keys.shift()!];
if (keys.length > 0) {
keys.forEach((k: string) => {
v = v ? v[k] : `{${key}}`;
});
}
return typeof v !== 'undefined' && v !== null ? v : str;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment