flask babel doesn't work with string returned by view

317 Views Asked by At

Sorry, I'm new on flask-babel, and also on flask! My flask code:

test.py

app = Flask(__name__)
app.config['BABEL_DEFAULT_LOCALE'] = 'en'
babel = Babel(app)

@app.route('/', methods=['GET'])
def hello_world():
    message = _(u'测试  页面')
    return render_template('index.html', message=message)

index.html

<h1>{{ _("测试") }}</h1>
<h2>{{ _("消息:%(m)s", m=message) }}</h2>

message.po

#: learnflask.py:23
msgid "测试  页面"
msgstr "test page"

#: templates/index.html:8
msgid "测试"
msgstr "Test"

#: templates/index.html:9
#, python-format
msgid "消息:%(m)s"
msgstr "message: %(m)s"

The result:

Test

消息:测试 页面

The first string is translate correctly, but not the second one. I want to know how to make it work. Please help. Thanks!

1

There are 1 best solutions below

0
On

OK. I find the answer. It's almost like you should delete the .mo file whenever you update the .po file. I delete message.mo, and use python compile -d translations to genrate a new message.mo, then it works fine!