customTranslate.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. // import translations from "./zh";
  2. //
  3. // export default function customTranslate(template, replacements) {
  4. // replacements = replacements || {};
  5. //
  6. // // Translate
  7. // template = translations[template] || template;
  8. //
  9. // // Replace
  10. // return template.replace(/{([^}]+)}/g, function(_, key) {
  11. // let str = replacements[key];
  12. // if (
  13. // translations[replacements[key]] !== null &&
  14. // translations[replacements[key]] !== "undefined"
  15. // ) {
  16. // // eslint-disable-next-line no-mixed-spaces-and-tabs
  17. // str = translations[replacements[key]];
  18. // // eslint-disable-next-line no-mixed-spaces-and-tabs
  19. // }
  20. // return str || "{" + key + "}";
  21. // });
  22. // }
  23. export default function customTranslate(translations) {
  24. return function (template, replacements) {
  25. replacements = replacements || {};
  26. // 将模板和翻译字典的键统一转换为小写进行匹配
  27. const lowerTemplate = template.toLowerCase();
  28. const translation = Object.keys(translations).find(key => key.toLowerCase() === lowerTemplate);
  29. // 如果找到匹配的翻译,使用翻译后的模板
  30. if (translation) {
  31. template = translations[translation];
  32. }
  33. // 替换模板中的占位符
  34. return template.replace(/{([^}]+)}/g, function (_, key) {
  35. // 如果替换值存在,返回替换值;否则返回原始占位符
  36. return replacements[key] !== undefined ? replacements[key] : `{${key}}`;
  37. });
  38. };
  39. }