如何在Flask-WTForms render_kw中使用Flask-Babel gettext?

时间:2017-11-20 11:23:26

标签: python flask babel flask-wtforms flask-babel

我开始使用Babel与WTForms和Flask。下面我尝试使用用户名密码字段的占位符关键字来获取文本:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask_babel import gettext
from flask_wtf import FlaskForm
from wtforms import PasswordField, StringField
from wtforms.validators import DataRequired


class LoginForm(FlaskForm):
    username = StringField(label='username',
                           validators=[DataRequired()],
                           render_kw={"placeholder": gettext('Username')})
    password = PasswordField(label='password',
                             validators=[DataRequired()],
                             render_kw={"placeholder": gettext('Password')})

这是我的法语.po文件(当然已编译):

# French (France) translations for PROJECT.
# Copyright (C) 2017 ORGANIZATION
# This file is distributed under the same license as the PROJECT project.
# FIRST AUTHOR <EMAIL@ADDRESS>, 2017.
#
msgid ""
msgstr ""
"Project-Id-Version: PROJECT VERSION\n"
"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n"
"POT-Creation-Date: 2017-11-20 12:08+0100\n"
"PO-Revision-Date: 2017-11-20 12:10+0100\n"
"Language: fr_FR\n"
"Language-Team: fr_FR <LL@li.org>\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=utf-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Generated-By: Babel 2.5.1\n"
"Last-Translator: \n"
"X-Generator: Poedit 2.0.4\n"

#: app/forms.py:13
msgid "Username"
msgstr "Nom d’utilisateur"

#: app/forms.py:16
msgid "Password"
msgstr "Mot de passe"

#: app/templates/login.html:34
msgid "Login"
msgstr "Se connecter"

不幸的是,即使我用法语强制使用语言环境,这两个字段也会保留英语。我在Jinja2模板中为 Login 翻译工作了。

我写错了吗?

1 个答案:

答案 0 :(得分:1)

我认为你应该使用lazy_gettext()方法