Advertisement
adamatti

Template engine

Jan 27th, 2023
1,029
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. export class TemplateEngine {
  2.   /**
  3.    * Template engine.
  4.    * @see https://stackoverflow.com/questions/30003353/can-es6-template-literals-be-substituted-at-runtime-or-reused
  5.    * @see https://gist.github.com/tmarshall/31e640e1fa80c597cc5bf78566b1274c
  6.    *
  7.    * @param templateString The template string, e.g "Hello ${name}"
  8.    * @param templateVars Map with variables, e.g { name: "John" }
  9.    * @returns The template string with variables replaced, e.g "Hello John"
  10.    */
  11.   static fillTemplate(templateString: string, templateVars: any): string {
  12.     const handler = new Function(
  13.       'vars',
  14.       [
  15.         'const tagged = ( ' + Object.keys(templateVars).join(', ') + ' ) =>',
  16.         '`' + templateString + '`',
  17.         'return tagged(...Object.values(vars))',
  18.       ].join('\n'),
  19.     );
  20.  
  21.     return handler(templateVars);
  22.   }
  23. }
  24.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement