Next-translate: Fallback Language support

Created on 18 May 2020  路  4Comments  路  Source: vinissimus/next-translate

It would be great to have support for fallback translations if the current language locale file is missing a given translation key, but exists on the default language.

enhancement

Most helpful comment

Great thank for that snippet, I'll give it a shot.
In my opinion, fallback languages, or an easy to implement alternative like the above, is a must-have for a i18n library.

All 4 comments

The problem of this approach is that it implies downloading at least two language dictionaries instead of only the current language dictionary. So by default I'd keep the current behavior, which is lighter.

This can be implemented right now outside the library:

hooks/useTranslationWithFallback.js:

import useTranslation from 'next-translate/useTranslation'

const fallbacks = {
  'common': 'commonFbk'
}

export default function useTranslationWithFallback() {
  const { t, lang } = useTranslation()

  return {
     t: (ns, key, ...args) => {
       const currentText = `${ns}:${key}`
       const fallbackText = `${fallbacks[ns]}:${key}`
       const currentTranslation = t(currentText, ...args)

       if(currentTranslation === currentText) return t(fallbackText, ...args)
       return currentTranslation
     },
     lang,
  }
}

In your page:

import React from 'react'
import I18nProvider from 'next-translate/I18nProvider'
import useTranslationWithFallback from '../hooks/useTranslationWithFallback'

// Import English common.json as Fallback
import commonFbk from '../locales/en/common.json'

function PageContent() {
  const { t, lang } = useTranslationWithFallback()

  return (
    <div>
      <h1>{t('common', 'title')}</h1>
    </div>
  )
}

export default function Page() {
  const { lang } = useTranslation()

  return (
    <I18nProvider lang={lang} namespaces={{ commonFbk }}>
      <PageContent />
    </I18nProvider>
  )
}

If we see that it is a very demanded feature then we will consider introducing this hook and a more comfortable alternative. But for now I would avoid introducing this complexity into the library.

Great thank for that snippet, I'll give it a shot.
In my opinion, fallback languages, or an easy to implement alternative like the above, is a must-have for a i18n library.

Ok, it can be considered as a future feature then.

We added the missing logger now, I hope it helps to detect when a translation is missing

Was this page helpful?
0 / 5 - 0 ratings