Search code examples
pythonflask-babel

Flask babel: flask-table is not translated


I'm trying to translate a flask web project with babel (using Ubuntu 16.04/python 2.7.12). Everything seems to work fine, except for the tables. The names of the columns just won't be translated. Does anyone know how I get that to work?

My .py example:

from flask import Flask, render_template
from flask_script import Manager
from flask.ext.babel import Babel, gettext
from flask_table import Table, Col

app = Flask(__name__)
manager = Manager(app)
babel = Babel(app)

class ItemTable(Table):
    col1 = Col(gettext('Apple'))
    col2 = Col(gettext('Banana'))
    col3 = Col(gettext('Pear'))

class Item(object):
    def __init__(self, col1, col2, col3):
        self.col1 = col1
        self.col2 = col2
        self.col3 = col3

@babel.localeselector
def get_locale():
    return 'de'

@app.route('/')
def index():
    items = []
items.append(Item('bla', 'bla', 'bla'))
table = ItemTable(items)

    test = gettext("This is a string.")
    return render_template('index.html', test=test, table=table)

if __name__ == '__main__':
    app.run(debug=True)

And the html file:

<h1>{{gettext("Hello World!")}}</h1>
<h2>{{test}}</h2>
{{table}}

Here, I just want to test if the translation to German does work, so get_locale just returns 'de'.The translations folder and the babel.cfg are in place, the pybabel extract/init/compile works, the strings Apple/Banana/Pear even appear in the resulting messages.po file, where they are translated. But although "Hello World" and 'test' get translated when the page is loaded, the column strings do not.

Any idea what to do?


Solution

  • I found a solution, for anyone who will encounter the same problem. The key is to overwrite the constructor of ItemTable:

    class ItemTable(Table):
        col1 = Col('')
        col2 = Col('')
        col3 = Col('')
    
        def __init__(self, items):
            super(ItemTable, self).__init__(items)
            self.col3.name = gettext('Apple')
            self.col2.name = gettext('Banana')
            self.col3.name = gettext('Pear')
    

    The same actually applies to wtforms. This doesn't work:

    class TestForm(Form):
        field1 = TextField(gettext('fieldlabel1'))
        field2 = TextField(gettext('fieldlabel2'))
    

    But this does:

    class TestForm(Form):
        field1 = TextField('')
        field2 = TextField('')
    
        def __init__(self, formdata=None):
            if formdata:
                super(TestForm, self).__init__(formdata)
            else:
                super(TestForm, self).__init__()
            self.field1.label.text = gettext('fieldlabel1')
            self.field2.label.text = gettext('fieldlabel2')