Utility FunctionsLocales
determineLocale
determineLocale 函数 API 参考
概述
determineLocale 函数无需 GT class 实例,即可根据用户偏好在已批准的 locales 中选出最匹配的 locale。
参考资料
参数
Prop
Type
返回值
string | undefined - 最佳匹配的 locale;若无匹配则为 undefined
示例
内容协商(Content Negotiation)
import { determineLocale } from 'generaltranslation';
const approvedLocales = ['en-US', 'es-ES', 'fr-FR', 'de-DE'];
// 精确匹配
console.log(determineLocale('en-US', approvedLocales)); // 'en-US'
// 语言回退
console.log(determineLocale('en-GB', approvedLocales)); // 'en-US'
// 多个偏好设置
console.log(determineLocale(['fr-CA', 'es-MX'], approvedLocales)); // 'es-ES'
// 无匹配项
console.log(determineLocale('it-IT', approvedLocales)); // undefined说明
- 实现智能的 locale 协商
- 从已批准列表中返回首个精确匹配或语言级匹配
- 遵循输入数组中的偏好顺序
- 若未找到匹配则返回 undefined
- 对于 Web 应用的 locale 协商至关重要
下一步
- 使用 GT class 的 determineLocale方法
- 通过 requiresTranslation检查是否需要翻译
这份指南怎么样?

