1
0
Fork 0
mirror of https://github.com/terribleplan/next.js.git synced 2024-01-19 02:48:18 +00:00

Add support for fetching multiple translation files (#2743)

* Add support for fetching multiple translation files

* Cleanup
This commit is contained in:
whphhg 2017-08-13 02:28:20 +02:00 committed by Tim Neutkens
parent 7a5a6bcef2
commit 8acdae66d7
6 changed files with 58 additions and 11 deletions

View file

@ -0,0 +1,19 @@
import React from 'react'
import { translate } from 'react-i18next'
class Post extends React.Component {
constructor (props) {
super(props)
this.t = props.t
}
render () {
return (
<div>
{this.t('namespace1:greatMorning')}
</div>
)
}
}
export default translate(['namespace1'])(Post)

View file

@ -3,13 +3,18 @@ import { I18nextProvider } from 'react-i18next'
import startI18n from '../tools/startI18n'
import { getTranslation } from '../tools/translationHelpers'
import Title from '../components/Title'
import Post from '../components/Post'
// get language from query parameter or url path
const lang = 'id'
export default class Homepage extends Component {
static async getInitialProps () {
const translations = await getTranslation(lang, 'common', 'http://localhost:3000/static/locales/')
const translations = await getTranslation(
lang,
['common', 'namespace1'],
'http://localhost:3000/static/locales/'
)
return { translations }
}
@ -23,7 +28,10 @@ export default class Homepage extends Component {
render (props) {
return (
<I18nextProvider i18n={this.i18n}>
<div>
<Title />
<Post />
</div>
</I18nextProvider>
)
}

View file

@ -0,0 +1,3 @@
{
"greatMorning": "Pagi yang indah!"
}

View file

@ -0,0 +1,3 @@
{
"greatMorning": "Maravilhosa manhã!"
}

View file

@ -1,9 +1,15 @@
import i18n from 'i18next'
const startI18n = (file, lang) => i18n.init({
/**
* Initialize a i18next instance.
* @function startI18n
* @param {object} files - Translation files.
* @param {string} lang - Active language.
*/
const startI18n = (files, lang) => i18n.init({
lng: lang, // active language http://i18next.com/translate/
fallbackLng: 'pt',
resources: file,
resources: files,
ns: ['common'],
defaultNS: 'common',
debug: false

View file

@ -1,13 +1,21 @@
/* global fetch */
import 'isomorphic-fetch'
export async function getTranslation (lang, file, baseUrl) {
const response = await fetch(`${baseUrl}${lang}/${file}.json`)
const json = await response.json()
/**
* Fetch translation file(s).
* @function getTranslation
* @param {string} lang - Language to fetch.
* @param {array} files - Translation files to fetch.
* @param {string} baseUrl - Locale location.
* @return {object} Fetched translation files.
*/
export async function getTranslation (lang, files, baseUrl) {
let translation = {}
return {
[lang]: {
[file]: json
}
for (let file of files) {
const response = await fetch(`${baseUrl}${lang}/${file}.json`)
translation[file] = await response.json()
}
return { [lang]: translation }
}