I need to implement a new language on a website that was written in one language (for example, in English). Now I need to add the ability to change the language on the site, for example, choosing between English and Spanish or any other language.
My idea is to create a table in the database that contains “key,” “language 1,” “language 2.” Initially, when the site loads, I download all the records from the table and create a method in each parent component; this file will be used in all child components. The principle of this method is simple: before rendering the page, this method will be called in every place where there is a key. The key is the name of the variable that will replace the static text in the HTML or JS code.
Method:
babelfishTranslate(text) {
if (this.wordReplacements[text]) {
return this.wordReplacements[text];
} else {
return text;
}
}
Example:
<div class="align-items-center align-items-md-end d-flex justify-content-between">
<h5 class="fw-bold">
{{ $root.babelfishTranslate(incipitdata.titolo || "incipit1") }}, {{ nomeAzienda }}
</h5>
<div class="d-flex gap-3 align-items-center">
<div class="d-flex gap-3">
<div>{{ $root.babelfishTranslate("incipit2") }}</div>
<switcher
:idvalore="'modalitaPrivacy'"
:name="'modalitaPrivacy'"
:valore="modalitaPrivacy"
v-on:settavalore="settaValore"
:key="'modalitaPrivacy' + aggiornaSwitcher"
/>
</div>
<div
v-tooltip="$root.babelfishTranslate('incipit3')"
class="nascondiSeMobile"
:key="aggiornaTooltip"
>
<button class="fs-2 btn btn-aggiungi color-custom" @click="vaiInModalitaModifica">
<i class="fa-duotone fa-gear"></i>
</button>
</div>
</div>
</div>
$root.babelfishTranslate(‘incipit2’) calls the babelfishTranslate method, which looks in the global variable where there is a translation if the key has the value ‘incipit2’, and replaces it with the user’s chosen language.
Table:
| Key | English | Italian |
|---|---|---|
| incipit2 | Privacy mode | Modalità Privacy |
But there is a problem with all of this. Replacing all the written static text with these “keys,” variables that I will later record in the table with translations for “language 1” and “language 2.”
How can I find all the text in my project? If I wrote the project in Vue 2, using the Options API, and all the HTML code is written inside the “template” variable. Also, it needs to take into account full phrases, for example, “Welcome [username], do you want to add [product name] to the cart?”