Utility FunctionsLocales

determineLocale

determineLocale 函数 API 参考

概览

determineLocale 函数会基于用户偏好,从已批准的 locale 列表中选出最佳匹配的 locale,而无需 GT class 实例。


参考

参数

Prop

Type

返回值

string | undefined - 最佳匹配的 locale;若无匹配则为 undefined


示例

内容协商

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 协商至关重要

后续步骤

本指南如何?