简体   繁体   中英

How to translate javascript-files in Pylons

We're making an application by using Pylons and JQuery. We have used standard way of making translations, but it doesn't quite work with javascript.

The awkwardness of js-translation methods is that we should make duplicate processes for selecting languages etc.

Is there a proper support in Pylons for javascript-translations?

An alternative method is to use the pylons gettext to generate your own javascript string ids like this:

html template:

<script type="text/javascript">
   var i18n_strings = {
      hello_world = '${ugettext('Hello World!')}',
      goodbye_world = '${ugettext('Goodbye World!')}',
      enter_name = '${ugettext('Enter Name:')}'
   };
</script>

now in your javascript:

$('#some-elem').html( i18n_strings.hello_world );

I'm using that solution with Pylons and ExtJS, but i think you can easily, change JS function for your needs..

In Pylons controller i have method which exports all translations (you need polib for this - http://code.google.com/p/polib/ ):

import polib
from pylons.i18n import get_lang

...

## method in conttroller class
@jsonify
def get_trans(self):
    def get_trans():
        items = polib.mofile(os.path.join(config['pylons.paths']['root'], 'i18n/%s/LC_MESSAGES/app.mo' % get_lang()[0]))
        return [{'name': item.msgid, 'value': item.msgstr} for item in items]
    return {'translations' : get_trans()}

JavaScript part:

lang_store = new Ext.data.JsonStore({
    url: '/lang/get',
    root: 'translations',
    id: 'name',
    autoLoad: true,
    fields: ['name', 'value'],
});

gettext = _ = function(_key) {
    try {
        return lang_store.getById(_key).data.value
    } catch(e) {
        return _key + "**"
    }
}

Now you can use "gettext(STRING)" or "_(STRING)" function in JS and you'll get translated string, if there will be no translation, you'll get something like UNTRANSLATED_STRING** (with asterisks at the end) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM