angular-translate - Fallback language for determinePreferredLanguage()

≡放荡痞女 提交于 2019-12-08 14:43:26

问题


I use angular-translate in my app. How can I register a fallback language if the determinePreferredLanguage() returns a language key my code doesn't know?

I want to fall back to english if someone from e.g. Sweden visits my site (language key: sv). But since I haven't listed sv in my registerAvailableLanguageKeys function, it fails, and the language-keys are shown to the user instead of the translation.

$translateProvider
    .registerAvailableLanguageKeys(['da-dk','en-us'], {
        'en_US': 'en-us',
        'en_UK': 'en-us',
        'da': 'da-dk',
    })
    .determinePreferredLanguage();

回答1:


Using wildcards is the best solution, you can just set en_* as follows:

    $translateProvider.useStaticFilesLoader({
       prefix: 'locales/locale-',
       suffix: '.json'
    })   

    .registerAvailableLanguageKeys(['en','fr','pt'], {
       'en_*': 'en',
       'fr_*': 'fr',
       'pt_*': 'pt',
       '*': 'en'
    })

    .determinePreferredLanguage()

    .fallbackLanguage('en');

for files:

locales/locale-en.json
locales/locale-fr.json
locales/locale-pt.json



回答2:


Hey I had a similar issue to yours, the way I solved it was :

I added this to my app.config

  $translateProvider.useStaticFilesLoader({
      prefix: 'the/directory/locale-',
      suffix: '.json'
    })

  .registerAvailableLanguageKeys(['en'])

  .determinePreferredLanguage()

  .fallbackLanguage('en');

and this to my app.run:

$rootScope.changeLanguage = function() {
  if(/[a-z]{2}_[A-Z]{2}/.test($translate.use())) {
    $translate.fallbackLanguage($translate.use().split('_')[0]);
  }
}

that way if the browser detects a language such as fr_BE it will try to fall back to fr and then once again en, in your case you would want sv. Also having the registerAvailableLanguageKeys seems to stop the determinePreferredLanguage() causing an error with the non-existant file issue. I hope this helps someone.




回答3:


You can use $translateProvider.fallbackLanguage(['en-us']) to determine your fallback language, and $translateProvider.preferredLanguage(langKey)to set your preferred language.

Also note that fallbackLanguage() can have an array of languages as a parameter, which means you can have several ordered fallback languages.



来源:https://stackoverflow.com/questions/25566903/angular-translate-fallback-language-for-determinepreferredlanguage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!