Created
April 26, 2024 04:34
-
-
Save im4aLL/6893b9a051135c0289cf558097025802 to your computer and use it in GitHub Desktop.
Nano template engine
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
/** | |
* 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