Created
December 6, 2023 07:19
-
-
Save john-yuan/0c871a449b3f19cd5c2a0f9b3d880c1b to your computer and use it in GitHub Desktop.
This file contains 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
/** | |
* Render template string. | |
* | |
* @example | |
* renderTemplate( | |
* 'Hello {{name}}. The \\{{name}} will be replaced.', | |
* { name: 'Joe' } | |
* ) | |
* // Output: | |
* // Hello Joe. The {{name}} will be replaced. | |
* | |
* @param template The template string. | |
* @param values An object containing the values. | |
* @returns The rendered string. | |
*/ | |
export default function renderTemplate( | |
template: string, | |
values: Record<string, any> | |
) { | |
return template.replace( | |
/(^|[\s\S]){{([^\s}]+)}}/g, | |
(matched, prefix, key) => { | |
if (prefix === '\\') { | |
return '{{' + key + '}}' | |
} | |
if (key) { | |
const val = values[key] | |
return val === undefined ? matched : prefix + val | |
} | |
return matched | |
} | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment