Localization¶
The application uses the vue-i18n library to manage localization. Although the default and currently only available language is English, the setup allows for easy addition of other languages in the future.
Overview¶
Localization in this application is handled through the i18n instance, which is configured in the src/lang/index.js file. The language preference is determined by the user's browser settings or a cookie, with English (en) set as the default language.
How It Works¶
-
Language Files:
- The translations for each language are stored in separate files (
en.js,es.js, etc.) under thesrc/langdirectory. - Currently, only the
en.jsfile is populated with English translations.
- The translations for each language are stored in separate files (
-
Language Detection:
- The application checks for a
langcookie to determine the user's preferred language. - If no cookie is found, it defaults to English (
en).
- The application checks for a
-
Dynamic Language Switching:
- Although the application is currently limited to English, the
i18nsetup supports dynamic language switching by updating thelocaleproperty.
- Although the application is currently limited to English, the
-
Integration with Components:
- The
$tfunction is used in Vue components to fetch localized strings. For example:<span>{{ $t('menu.configuration') }}</span>
- The
Configuration¶
The i18n instance is configured in the src/lang/index.js file. Below is an overview of its setup:
import { createI18n } from 'vue-i18n';
import Cookies from 'js-cookie';
import enLocale from './en';
const messages = {
en: {
...enLocale
}
};
const i18n = createI18n({
locale: Cookies.get('lang') || 'en', // Default to English
messages
});
export default i18n;
Adding a New Language¶
To add a new language, follow these steps:
-
Create a Language File:
- Add a new file (e.g.,
es.jsfor Spanish) in thesrc/langdirectory. - Populate it with translations in the desired language.
- Add a new file (e.g.,
-
Update the
messagesObject:- Import the new language file in
src/lang/index.js. - Add it to the
messagesobject:import esLocale from './es'; const messages = { en: { ...enLocale }, es: { ...esLocale } };
- Import the new language file in
-
Set the Language:
- Update the
langcookie or set thelocaleproperty of thei18ninstance to the new language code.
- Update the
Example Usage¶
Here is an example of how localization is used in a Vue component:
<template>
<div>
<h1>{{ $t('menu.configuration') }}</h1>
<p>{{ $t('words.welcome') }}</p>
</div>
</template>
In the en.js file, the translations might look like this:
export default {
menu: {
configuration: 'Configuration'
},
words: {
welcome: 'Welcome'
}
};
Notes¶
- The current setup defaults to English but can be changed in the header but now only displays EN language.
- Adding support for additional languages requires creating translation files and updating the
messagesobject insrc/lang/index.js.