index.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. 'use strict';
  2. const {htmlEscape} = require('escape-goat');
  3. module.exports = (template, data) => {
  4. if (typeof template !== 'string') {
  5. throw new TypeError(`Expected a \`string\` in the first argument, got \`${typeof template}\``);
  6. }
  7. if (typeof data !== 'object') {
  8. throw new TypeError(`Expected an \`object\` or \`Array\` in the second argument, got \`${typeof data}\``);
  9. }
  10. // The regex tries to match either a number inside `{{ }}` or a valid JS identifier or key path.
  11. const doubleBraceRegex = /{{(\d+|[a-z$_][a-z\d$_]*?(?:\.[a-z\d$_]*?)*?)}}/gi;
  12. if (doubleBraceRegex.test(template)) {
  13. template = template.replace(doubleBraceRegex, (_, key) => {
  14. let result = data;
  15. for (const property of key.split('.')) {
  16. result = result ? result[property] : '';
  17. }
  18. return htmlEscape(String(result));
  19. });
  20. }
  21. const braceRegex = /{(\d+|[a-z$_][a-z\d$_]*?(?:\.[a-z\d$_]*?)*?)}/gi;
  22. return template.replace(braceRegex, (_, key) => {
  23. let result = data;
  24. for (const property of key.split('.')) {
  25. result = result ? result[property] : '';
  26. }
  27. return String(result);
  28. });
  29. };