GT ClassMethodsLocales
determineLocale
GT determineLocale 方法的 API 参考
概览
determineLocale 方法会根据用户偏好,从已批准的 locales 列表中选出最佳匹配的 locale。
当没有精确匹配时,它会进行 locale 协商以确定最合适的 locale。
const gt = new GT({
  sourceLocale: 'en-US',
  locales: ['en-US', 'es-ES', 'fr-FR', 'de-DE']
});
// 精确匹配
console.log(gt.determineLocale('en-US')); // 'en-US'
// 语言降级(fallback)
console.log(gt.determineLocale('en-GB')); // 'en-US'(最接近的英语变体)
// 多重偏好
console.log(gt.determineLocale(['fr-CA', 'es-MX', 'en-US'])); // 'es-ES'(最接近的西班牙语)
// 无匹配
console.log(gt.determineLocale('it-IT')); // undefined参考资料
参数
Prop
Type
返回
string | undefined - 最佳匹配的 locale;如果未找到匹配,则为 undefined
示例
用户 locale 协商
const gt = new GT({
  sourceLocale: 'en-US',
  locales: ['en-US', 'en-GB', 'es-ES', 'fr-FR']
});
// 模拟浏览器 Accept-Language 头
const userPreferences = ['fr-CA', 'en-GB', 'en'];
const bestMatch = gt.determineLocale(userPreferences);
console.log(bestMatch); // 按偏好顺序匹配得到 'fr-FR'备注
- 从已批准的 locales 中返回首个精确匹配
- 当没有对应的区域时,回退为仅按语言匹配
- 遵循输入数组中的偏好顺序
- 若未找到合适的匹配,则返回 undefined
- 对在 Web 应用中实现 locale 协商至关重要
后续步骤
- 使用 requires-translation检查是否需要翻译
- 使用 is-same-language比较是否为同一语言
这份指南怎么样?

