jami-docs/_templates/language-selector.html

66 lines
3.1 KiB
HTML

<select id="language-selector" onchange="handleChangeLanguage();" style="width: 100%; position: absolute;">
{% for lang, lang_url in languages %}
<option value="{{ lang_url }}">
{{ lang }}
</option>
{% endfor %}
</select>
<script>
// Should be consistent with the list `languages` in conf.py
let available_lang_code = ['/ar/', '/bg/', '/bn/', '/ca/', '/da/', '/de/', '/el/', '/en_US/', '/eo/', '/es/', '/et/', '/eu/', '/fa/', '/fi/', '/fr/', '/he/', '/hi/', '/hi_IN/', '/hr/', '/hu/', '/id/', '/it/', '/ja/', '/ko/', '/lt/', '/ne/', '/nl/', '/pl/', '/pt/', '/pt_BR/', '/pt_PT/', '/ro/', '/ru/', '/si/', '/sk/', '/sl/', '/sr/', '/sv/', '/ta/', '/te/', '/tr/', '/vi/', '/zh_CN/', '/zh_TW/'];
let selector = document.getElementById('language-selector');
let site_domain = /docs\.jami\.net/;
function handleChangeLanguage(e) {
let target_lang_code = selector.value;
let current_url = window.location.href;
let found_site_domain = current_url.match(site_domain);
// Replace lang code
window.location.href = current_url.slice(0, found_site_domain.index + found_site_domain[0].length) + '/' + target_lang_code + '/' + current_url.slice(found_site_domain.index + found_site_domain[0].length + getCurrentLangCode().length + 2);
}
//Get current lang code from the URL
function getCurrentLangCode() {
let current_url = window.location.href;
let current_lang_code = '';
for (let i = 0; i < available_lang_code.length; ++i) {
if (current_url.indexOf(available_lang_code[i]) !== -1) {
// exclude the leading and trailing '/''
current_lang_code = available_lang_code[i].slice(1, -1);
}
}
return current_lang_code;
}
// Use system language if avaiable lang codes not found in the URL
document.addEventListener('DOMContentLoaded', function () {
let current_lang_code = getCurrentLangCode();
//Most modern browsers use hypen (IETF language tags) as a separator. Transifex uses underscore. Underscores are preferred for the convenience of working with Transifex.
let browserLang = navigator.language.replace('-', '_') || 'en_US';
let current_url = window.location.href;
let found_site_domain = current_url.match(site_domain);
if(current_lang_code === ''){
let lang = browserLang;
// if browser language is not supported, use en_US
if(available_lang_code.indexOf(`/${browserLang}/`) === -1){
lang = 'en_US';
}
window.location.href = current_url.slice(0, found_site_domain.index + found_site_domain[0].length) + '/' + lang + current_url.slice(found_site_domain.index + found_site_domain[0].length);
}
})
//Display current language in language selector on page load
document.addEventListener('DOMContentLoaded', function () {
let current_lang_code = getCurrentLangCode();
document.querySelectorAll(`option[value='${current_lang_code}']`).forEach(option => {
option.setAttribute('selected', '');
})
})
</script>