我正在尝试使用babel(使用Ubuntu 16.04 / python 2.7.12)翻译烧瓶Web项目。除了桌子,一切似乎都很好。列的名称将不会被翻译。有谁知道我是如何工作的?
我的.py示例:
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)
和html文件:
<h1>{{gettext("Hello World!")}}</h1>
<h2>{{test}}</h2>
{{table}}
在这里,我只想测试德语的翻译是否有效,所以get_locale只返回'de'。翻译文件夹和babel.cfg到位,pybabel extract / init / compile工作,字符串Apple / Banana / Pear甚至出现在生成的messages.po文件中,它们被翻译。但是,虽然“Hello World”和“test”在页面加载时被翻译,但列字符串却没有。
知道该怎么做?
答案 0 :(得分:1)
我为遇到同样问题的人找到了解决方案。关键是要覆盖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')
同样实际上适用于wtforms。这不起作用:
class TestForm(Form):
field1 = TextField(gettext('fieldlabel1'))
field2 = TextField(gettext('fieldlabel2'))
但这样做:
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')
答案 1 :(得分:0)
您可以使用lazy_gettext代替gettext并将其保持原样。
from flask.ext.babel import lazy_gettext
from flask_table import Table, Col
class ItemTable(Table):
col1 = Col(gettext('Apple'))
col2 = Col(gettext('Banana'))
col3 = Col(gettext('Pear'))