Hay Axe,
Here is a quick solution for static pages, not for dynamic pages. For dynamic pages you will need to modify this solution a bit. The main difference is that on dynamic pages you need to handle differently texts that are connected to a dataset vs non connected texts.
I have created a site with three text elements and two buttons -
Then I have created a collection with the following fields -
I did not write all the content in this collection - I have let the site actually generate most of the collection content - and I had only to write the FR version.
Lets look at the code.
The code has two parts - inserting into the collection all the data for the EN version, reading it from the site design, and making translations.
The first part -
import wixData from "wix-data";
import wixLocation from "wix-location";
let pageId;
$w.onReady(() => {
pageId = wixLocation.path.join('/') || 'home';
prepereTranslations();
})
function prepereTranslations() {
$w('Text').forEach( async (txt) => {
let item = await wixData.get('translations', pageId + '.' + txt.id);
if (!item)
wixData.insert('translations', {
_id: pageId + '.' + txt.id,
elementId: '#' + txt.id,
pageId: pageId,
en: txt.text
});
})
}
The $w(‘Text’) selector lets me get all the Text elements on the page. With that, I check that each has an entry in the translations database and create one if it does not exist. I have added the elementId, pageId and _id to the saved item to make sure I can fetch the translations per page and per element.
The second part -
async function loadTranslations(lang) {
let res = await wixData.query('translations')
.eq('pageId', pageId)
.find();
res.items.forEach(item => {
$w(item.elementId).text = item[lang];
});
}
export function en_click(event, $w) {
loadTranslations('en');
}
export function fr_click(event, $w) {
loadTranslations('fr');
}
Clicking on the buttons, I read the translations for a page, fetch the element and set it’s text to the text read from the database.