Skip to content

Instantly share code, notes, and snippets.

@sibelius
Forked from elsangedy/component.js
Created March 7, 2019 17:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sibelius/3eb9b2d5f22da0a948156fc93060f0b3 to your computer and use it in GitHub Desktop.
Save sibelius/3eb9b2d5f22da0a948156fc93060f0b3 to your computer and use it in GitHub Desktop.
i18next
t('global_datetime_formatter', { date: myDate })
t('global_currency_formatter', { value: myValue })
import i18n from 'i18next'
import Backend from 'i18next-xhr-backend'
import LanguageDetector from 'i18next-browser-languagedetector'
import { reactI18nextModule } from 'react-i18next'
import * as R from 'ramda'
import dateFnsFormat from 'date-fns/format'
const getPattern = R.compose(
R.prop(1),
R.split('|')
)
i18n
// load translation using xhr -> see /public/locales
// learn more: https://github.com/i18next/i18next-xhr-backend
.use(Backend)
// detect user language
// learn more: https://github.com/i18next/i18next-browser-languageDetector
.use(LanguageDetector)
// pass the i18n instance to react-i18next.
// .use(initReactI18n)
.use(reactI18nextModule)
// init i18next
// for all options read: https://www.i18next.com/overview/configuration-options
.init({
debug: false,
fallbackLng: 'pt-BR',
interpolation: {
escapeValue: false, // not needed for react as it escapes by default
format: (value, format, lang) => {
if (R.or(R.isNil, R.isEmpty)(value)) {
return ''
}
const getValue = R.cond([
[
R.contains('date'),
R.compose(
pattern => dateFnsFormat(value, pattern),
getPattern
)
],
[
R.contains('currency'),
R.compose(
pattern =>
R.compose(
R.trim,
R.replace(' ', ''),
R.replace(' ', ''),
R.replace(pattern, ''),
pattern =>
new Intl.NumberFormat(lang, {
style: 'currency',
currency: pattern,
currencyDisplay: 'code'
}).format(value)
)(pattern),
getPattern
)
],
[R.contains('replaceDotToComa'), R.always(R.replace('.', ',', value.toString()))],
[R.T, R.always(value)]
])
return getValue(format)
}
}
})
export default i18n
{
"global_currency": "R$",
"global_currency_formatter": "$t(global_currency) {{value, currency|BRL}}",
"global_date_formatter": "{{date, date|dd/MM/yyyy}}",
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment