SimpleHTMLLocalizer
SimpleHTMLLocalizer copied to clipboard
Use with select `option` elements
Currently you can't use this to localize <option> elements in <select>. Adding a localized-option element would allow this:
customElements.define('localized-option', LocalizedOptionElement, { extends: 'option' });
class LocalizedOptionElement extends HTMLOptionElement {
constructor() {
super();
}
connectedCallback() {
var key = this.hasAttribute('key') ? this.getAttribute('key') : '';
var lang = this.hasAttribute('lang') ? this.getAttribute('lang') : getLang();
this.innerHTML = translate(key, lang);
}
}
It's used like this.
<select class="form-select" name="sel" id="my-select">
<option is="localized-option" key="Off" value="0"></option>
<option is="localized-option" key="On" value="1"></option>
I'd also suggest changing translate so that missing dictionary keys translate to the key name automatically.
function translate(key, lang) {
var dict = (lang in dictionary) ? dictionary[lang] : dictionary['_']
return key in dict ? dict[key] : key;
}
Thanks for this suggestion, it works well.
I really like this library and have been using it for a few projects now. Since there does not seem to be any activity in this repo, I created a fork: https://github.com/foxblock/SimpleHTMLLocalizer That includes your addition of the localized option element, but also a heap of other features (while keeping the library as simple as it was).
Cheers!