Namespaces
Namespaces are a way to organize translation files, allowing us to separate them by functionality or by type of content.
By default, we have a namespace
called translation
for all our translations, which is in the file src/locales/es/translation.json
.
{
"Hola Este es un ejemplo de traduccion base": "Hola Este es un ejemplo de traduccion base"
}
-
If we want to separate our translations by functionality, we can create a new
namespace
calledmessages
.src/locales/es/messages.json{
"Mensaje de ejemplo": "Mensaje de ejemplo"
} -
If we want to separate our translations by type of content, we can create a new
namespace
calledpages
.src/locales/es/pages.json{
"Texto en la pagina": "Texto en la pagina"
}
Configuration in our hook
In our translation hook
, we pass the namespace
parameter to use the one we want, but by default, we pass translation
.
"use client";
import { useTypedTranslation } from 'translate-projects-nextjs/hooks';
import es from '@/locales/es/translation.json';
type Tylelang = typeof es
export const useTranslation = (ns: string = 'translation') => {
return useTypedTranslation<Tylelang>(ns)
}
Using namespaces
We can use namespaces in our component.
In this case, we are going to use the namespace
messages
.
import { useTranslation } from '@/hooks/useTranslation'; We import our hook.
function App() {
const { t } = useTranslation('messages'); //We use the namespace
return (
<div>
<header>
{t('Mensaje de ejemplo')}
</header>
</div>
);
}
export default App;
Another way to use the namespace
is by passing it as a parameter in the useTranslation
function.
import { useTranslation } from '@/hooks/useTranslation'; We import our hook.
function App() {
const { t } = useTranslation(); //We don't pass the namespace.
return (
<div>
<header>
{t('Mensaje de ejemplo',{ns: 'messages'})} //We pass the namespace.
</header>
</div>
);
}