Skip to content

Instantly share code, notes, and snippets.

@john-yuan
Created December 6, 2023 07:19
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 john-yuan/0c871a449b3f19cd5c2a0f9b3d880c1b to your computer and use it in GitHub Desktop.
Save john-yuan/0c871a449b3f19cd5c2a0f9b3d880c1b to your computer and use it in GitHub Desktop.
/**
* 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