0
# Translation Functions
1
2
String translation functions supporting pluralization, context, and lazy evaluation for Flask applications.
3
4
## Capabilities
5
6
### Basic Translation
7
8
Translate strings with variable substitution.
9
10
```python { .api }
11
def gettext(string, **variables):
12
"""
13
Translate a string with current locale.
14
15
Parameters:
16
- string: String to translate
17
- **variables: Variables for string formatting
18
19
Returns:
20
Translated string
21
22
Usage:
23
gettext('Hello World!')
24
gettext('Hello %(name)s!', name='John')
25
"""
26
27
# Common alias for gettext
28
_ = gettext
29
```
30
31
### Plural Translation
32
33
Translate strings with plural forms based on count.
34
35
```python { .api }
36
def ngettext(singular, plural, num, **variables):
37
"""
38
Translate string with plural forms.
39
40
Parameters:
41
- singular: Singular form string
42
- plural: Plural form string
43
- num: Number determining singular/plural
44
- **variables: Variables for string formatting (num is automatically added)
45
46
Returns:
47
Translated string in appropriate form
48
49
Usage:
50
ngettext('%(num)d item', '%(num)d items', count)
51
ngettext('One apple', '%(num)d apples', apple_count)
52
"""
53
```
54
55
### Context Translation
56
57
Translate strings with context to disambiguate identical strings.
58
59
```python { .api }
60
def pgettext(context, string, **variables):
61
"""
62
Translate string with context.
63
64
Parameters:
65
- context: Context string for disambiguation
66
- string: String to translate
67
- **variables: Variables for string formatting
68
69
Returns:
70
Translated string
71
72
Usage:
73
pgettext('button', 'Save') # Save button
74
pgettext('menu', 'Save') # Save menu item
75
"""
76
77
def npgettext(context, singular, plural, num, **variables):
78
"""
79
Translate string with context and plural forms.
80
81
Parameters:
82
- context: Context string for disambiguation
83
- singular: Singular form string
84
- plural: Plural form string
85
- num: Number determining singular/plural
86
- **variables: Variables for string formatting
87
88
Returns:
89
Translated string in appropriate form
90
"""
91
```
92
93
### Lazy Translation
94
95
Return lazy-evaluated translation objects that resolve when converted to strings.
96
97
```python { .api }
98
def lazy_gettext(string, **variables):
99
"""
100
Return lazy-evaluated translation.
101
102
Parameters:
103
- string: String to translate
104
- **variables: Variables for string formatting
105
106
Returns:
107
LazyString object that translates when converted to string
108
109
Usage:
110
lazy_message = lazy_gettext('Hello World!')
111
# Translation happens when lazy_message is used as string
112
"""
113
114
def lazy_ngettext(singular, plural, num, **variables):
115
"""
116
Return lazy-evaluated plural translation.
117
118
Parameters:
119
- singular: Singular form string
120
- plural: Plural form string
121
- num: Number determining singular/plural
122
- **variables: Variables for string formatting
123
124
Returns:
125
LazyString object
126
"""
127
128
def lazy_pgettext(context, string, **variables):
129
"""
130
Return lazy-evaluated context translation.
131
132
Parameters:
133
- context: Context string
134
- string: String to translate
135
- **variables: Variables for string formatting
136
137
Returns:
138
LazyString object
139
"""
140
141
def lazy_npgettext(context, singular, plural, num, **variables):
142
"""
143
Return lazy-evaluated context plural translation.
144
145
Parameters:
146
- context: Context string
147
- singular: Singular form string
148
- plural: Plural form string
149
- num: Number determining singular/plural
150
- **variables: Variables for string formatting
151
152
Returns:
153
LazyString object
154
"""
155
```
156
157
### Translation Context Access
158
159
Get translation objects and context information.
160
161
```python { .api }
162
def get_translations():
163
"""
164
Get translations object for current request.
165
166
Returns:
167
babel.support.Translations or NullTranslations object
168
"""
169
```
170
171
## Types
172
173
```python { .api }
174
class LazyString:
175
"""
176
Lazy-evaluated string that resolves translation when used.
177
178
Supports all string operations and converts to string automatically
179
when used in string contexts. Implements full string interface.
180
"""
181
def __init__(self, func, *args, **kwargs): ...
182
def __str__(self): ...
183
def __repr__(self): ...
184
def __html__(self): ...
185
def __len__(self): ...
186
def __getitem__(self, key): ...
187
def __iter__(self): ...
188
def __contains__(self, item): ...
189
def __add__(self, other): ...
190
def __radd__(self, other): ...
191
def __mul__(self, other): ...
192
def __rmul__(self, other): ...
193
def __mod__(self, other): ...
194
def __rmod__(self, other): ...
195
def __lt__(self, other): ...
196
def __le__(self, other): ...
197
def __eq__(self, other): ...
198
def __ne__(self, other): ...
199
def __gt__(self, other): ...
200
def __ge__(self, other): ...
201
def __hash__(self): ...
202
def __getattr__(self, attr): ...
203
```
204
205
## Usage Examples
206
207
### Basic Translation
208
209
```python
210
from flask_babel import gettext as _
211
212
# Simple translation
213
message = _('Welcome to our site!')
214
215
# With variables
216
greeting = _('Hello %(username)s!', username=current_user.name)
217
```
218
219
### Plural Forms
220
221
```python
222
from flask_babel import ngettext
223
224
def show_results(count):
225
message = ngettext(
226
'Found %(num)d result',
227
'Found %(num)d results',
228
count
229
)
230
return message
231
```
232
233
### Context Disambiguation
234
235
```python
236
from flask_babel import pgettext
237
238
# Different contexts for same English word
239
save_button = pgettext('button', 'Save')
240
save_menu = pgettext('menu', 'Save')
241
save_file = pgettext('file action', 'Save')
242
```
243
244
### Lazy Evaluation
245
246
```python
247
from flask_babel import lazy_gettext
248
249
# Define at module level
250
ERROR_MESSAGES = {
251
'required': lazy_gettext('This field is required'),
252
'invalid': lazy_gettext('Invalid input'),
253
}
254
255
# Translation happens when message is used
256
def validate_field(value):
257
if not value:
258
return str(ERROR_MESSAGES['required']) # Translates here
259
```
260
261
### Form Integration
262
263
```python
264
from flask_wtf import FlaskForm
265
from wtforms import StringField, SubmitField
266
from wtforms.validators import DataRequired
267
from flask_babel import lazy_gettext as _l
268
269
class MyForm(FlaskForm):
270
username = StringField(_l('Username'), validators=[DataRequired()])
271
submit = SubmitField(_l('Submit'))
272
```