In my extension I have a list of languages from which the user can choose (these are target languages for a translation tool). In trying to add localisation to this extension I have created entries in the messages file (this one is for Spanish):

_locales/es/messages.json

"extLang_af": {
    "message": "Africaans",
    "description": "Localised name for Afrikaans"
    },
"extLang_sq": {
    "message": "Alban\u00E9s",
    "description": "Localised name for Albanian"
    },
"extLang_ar": {
    "message": "\u00C1rabe",
    "description": "Localised name for Arabic"
    },
    ...

In the options.html file I have the following:

<select id="target">
 <option id="af">Afrikaans</option>
 <option id="sq">Albanian</option>
 <option id="ar">Arabic</option>
 ...
</select>
<script src="options.js"></script>

And I have javascript in options.js to change the names.

var langs = ['af', 'sq', 'ar', ...]
langs.forEach(function(lang) {
    var msg_name = "extLang_" + lang;
    var localised_lang = chrome.i18n.getMessage(msg_name);
    document.getElementById(lang).text=localised_lang;
});

My problem is that because the original <select> options are sorted for English, the language options are out of order when they have been translated. I have considered that it could be solved by generating the <select> options programmatically from a sorted list stored in the _locales/es/messages.json file, but don't know whether that is the best approach. Is there a standard way of approaching this problem?

有帮助吗?

解决方案

I'm sure this isn't pretty but it seems to work. Replace the javascript in options.js with this:

var langs = ['af', 'sq', 'ar', ...]
var langsToSort = [];
langs.forEach(function(lang) {
    var msg_name = "extLang_" + lang;
    var localisedLang = chrome.i18n.getMessage(msg_name);
    langsToSort.push([localisedLang, lang]);
});
var sortedLangs = langsToSort.sort(function(a,b) {
    return a[0].localeCompare(b[0]);
});
// Get rid of current contents of the select dropdown
document.getElementById("target").innerHTML = "";
// Set the dropdown elements
sortedLangs.forEach(function(lang) {
    var x = document.getElementById("target");
    var optn = document.createElement("OPTION");
    optn.text = lang[0];  
    optn.value = lang[1];  
    x.add(optn);  
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top