Question

Possibly i am overlooking an obvious solution or thinking the wrong way...

I have a limited amount of text, words in a database, that I want to display translated to users in a flask/jinja/babel webapp. eg. "running" is a possible value of an "activity" column and that should be "laufen" for my german users.

Words in templates and code are extracted and put into the catalog, but how do i get additional words into the catalog? Is there a simple text file extractor?

The only thing i could think of is, just create a .py file and put lots of _('...') lines in them, but that feels just wrong... is it?

Was it helpful?

Solution

I created a messages.txt with my "words" like gettext function calls:

_('cycling')
_('running')

and added it to my babel.cfg as python source:

[python: messages.txt]

plain, simple, stupid, but works.

OTHER TIPS

First, start with http://flask.pocoo.org/snippets/4/.

Secondly, you need to store these 'limited' values as integers or enums in database and then create the lookup table for all these enums in code (so Babel knows about them):

i18n_val = {0: _('running'), ...}
# Or multi-level dict with different categories:
i18n_all = {
  'activity': {
     0: _('running'), ...
  'foo': {
     0: _('bar..'), ...
  }
}

And accessing the translated string from template is now as simple as:

{{ i18n_val[obj.activity] }}
{{ i18n_all['activity'][obj.activity] }}

In order to make the i18n_val and i18n_all variables available for all the templates, just register them with context processors.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top