index.js 485 B

1234567891011121314151617181920212223
  1. 'use strict';
  2. module.exports = (tpl, data) => {
  3. if (typeof tpl !== 'string') {
  4. throw new TypeError(`Expected a string in the first argument, got ${typeof tpl}`);
  5. }
  6. if (typeof data !== 'object') {
  7. throw new TypeError(`Expected an Object/Array in the second argument, got ${typeof data}`);
  8. }
  9. const re = /{(.*?)}/g;
  10. return tpl.replace(re, (_, key) => {
  11. let ret = data;
  12. for (const prop of key.split('.')) {
  13. ret = ret ? ret[prop] : '';
  14. }
  15. return ret || '';
  16. });
  17. };