5

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?

desertnaut
  • 57,590
  • 26
  • 140
  • 166
Florian
  • 2,562
  • 5
  • 25
  • 35
  • Are these words in the database defined as enums? – plaes Jan 15 '12 at 16:18
  • Yes, but don't limit yourself to enums or databases for that matter. Another scenario might be an external system, maybe sending JSON to my system, with certain words, that i need translated, which *never* appear in *my* code, but only in the incoming messages. I *know* those words from let's say the API specs, but I want to avoid putting them in my code as `_('word')`, just to be picked up by gettext. I guess I'll just use a pain text file with a word per line and write my own extraction function for it. – Florian Jan 15 '12 at 21:05

2 Answers2

4

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.

Florian
  • 2,562
  • 5
  • 25
  • 35
2

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.

plaes
  • 31,788
  • 11
  • 91
  • 89
  • That second part is the one I have a problem with. I do not want to take all that text from the database and copy it somewhere in code by hand. That last bit, I actually solved by using a "|trans" filter, that looks up translations. – Florian Jan 15 '12 at 20:53