customTranslate.js 1.32 KB
Newer Older
sunhongwei's avatar
sunhongwei committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
// import translations from "./zh";
//
// export default function customTranslate(template, replacements) {
//   replacements = replacements || {};
//
//   // Translate
//   template = translations[template] || template;
//
//   // Replace
//   return template.replace(/{([^}]+)}/g, function(_, key) {
//     let str = replacements[key];
//     if (
//       translations[replacements[key]] !== null &&
//       translations[replacements[key]] !== "undefined"
//     ) {
//       // eslint-disable-next-line no-mixed-spaces-and-tabs
//       str = translations[replacements[key]];
//       // eslint-disable-next-line no-mixed-spaces-and-tabs
//     }
//     return str || "{" + key + "}";
//   });
// }

export default function customTranslate(translations) {
  return function(template, replacements) {
    replacements = replacements || {};
    // Translate
    template = translations[template] || template;

    // Replace
    return template.replace(/{([^}]+)}/g, function(_, key) {
      let str = replacements[key];
      if (translations[replacements[key]] !== null && translations[replacements[key]] !== undefined) {
        // eslint-disable-next-line no-mixed-spaces-and-tabs
        str = translations[replacements[key]];
        // eslint-disable-next-line no-mixed-spaces-and-tabs
      }
      return str || "{" + key + "}";
    });
  };
}