Published:
Create multi language functionality using javascript
Edit this postFirst we create an object containing all translate texts
const translates = {
fa: {
blog: {
header: {
title: "وبلاگ محمدرضا خسرویان",
},
},
},
en: {
blog: {
header: {
title: "Mohammad Reza Khosravian Blog",
},
},
}
}
Then we create a function to get lang attribute of html documente element
const getHtmlLang = () => document.documentElement.lang
Finally we create a t
(translate) function
function t(key, lang) {
// get document language
const language = lang || getHtmlLang() || "en";
// take out locale translate texts
const texts = translates[language];
// find text
return key.split('.').reduce((o, i) => {
if (o) return o[i]
}, texts)
}
Usage:
console.log( t("blog.header.title") ) // 'Mohammad Reza Khosravian Blog'
// Or
console.log( t("blog.header.title", "fa") ) // 'وبلاگ محمدرضا خسرویان'
// Or
console.log( t("blog.header.something", "en") ) // undefind