0
# Tests and Conditionals
1
2
39 built-in tests for template conditional logic including type checking, value comparison, and meta-testing. Tests are used in {% if %} statements and can be combined with logical operators.
3
4
## Capabilities
5
6
### Type Testing
7
8
Tests for checking object types and characteristics.
9
10
```python { .api }
11
def boolean(value):
12
"""
13
Check if value is a boolean.
14
15
Parameters:
16
value: Input value
17
18
Returns:
19
bool: True if value is boolean
20
"""
21
22
def callable(obj):
23
"""
24
Check if object is callable.
25
26
Parameters:
27
obj: Input object
28
29
Returns:
30
bool: True if object is callable
31
"""
32
33
def defined(value):
34
"""
35
Check if value is defined (not undefined).
36
37
Parameters:
38
value: Input value
39
40
Returns:
41
bool: True if value is defined
42
"""
43
44
def undefined(value):
45
"""
46
Check if value is undefined.
47
48
Parameters:
49
value: Input value
50
51
Returns:
52
bool: True if value is undefined
53
"""
54
55
def float(value):
56
"""
57
Check if value is a float.
58
59
Parameters:
60
value: Input value
61
62
Returns:
63
bool: True if value is float
64
"""
65
66
def integer(value):
67
"""
68
Check if value is an integer.
69
70
Parameters:
71
value: Input value
72
73
Returns:
74
bool: True if value is integer
75
"""
76
77
def iterable(value):
78
"""
79
Check if value is iterable.
80
81
Parameters:
82
value: Input value
83
84
Returns:
85
bool: True if value is iterable
86
"""
87
88
def mapping(value):
89
"""
90
Check if value is a mapping (dict-like).
91
92
Parameters:
93
value: Input value
94
95
Returns:
96
bool: True if value is mapping
97
"""
98
99
def none(value):
100
"""
101
Check if value is None.
102
103
Parameters:
104
value: Input value
105
106
Returns:
107
bool: True if value is None
108
"""
109
110
def number(value):
111
"""
112
Check if value is a number.
113
114
Parameters:
115
value: Input value
116
117
Returns:
118
bool: True if value is number
119
"""
120
121
def sequence(value):
122
"""
123
Check if value is a sequence.
124
125
Parameters:
126
value: Input value
127
128
Returns:
129
bool: True if value is sequence
130
"""
131
132
def string(value):
133
"""
134
Check if value is a string.
135
136
Parameters:
137
value: Input value
138
139
Returns:
140
bool: True if value is string
141
"""
142
```
143
144
### Value Testing
145
146
Tests for checking specific value characteristics and properties.
147
148
```python { .api }
149
def even(value):
150
"""
151
Check if number is even.
152
153
Parameters:
154
value: Input number
155
156
Returns:
157
bool: True if number is even
158
"""
159
160
def odd(value):
161
"""
162
Check if number is odd.
163
164
Parameters:
165
value: Input number
166
167
Returns:
168
bool: True if number is odd
169
"""
170
171
def divisibleby(value, num):
172
"""
173
Check if value is divisible by number.
174
175
Parameters:
176
value: Input number
177
num: Divisor number
178
179
Returns:
180
bool: True if value is divisible by num
181
"""
182
183
def escaped(value):
184
"""
185
Check if value is escaped (Markup object).
186
187
Parameters:
188
value: Input value
189
190
Returns:
191
bool: True if value is escaped
192
"""
193
194
def false(value):
195
"""
196
Check if value is falsy (evaluates to False).
197
198
Parameters:
199
value: Input value
200
201
Returns:
202
bool: True if value is falsy
203
"""
204
205
def true(value):
206
"""
207
Check if value is truthy (evaluates to True).
208
209
Parameters:
210
value: Input value
211
212
Returns:
213
bool: True if value is truthy
214
"""
215
216
def lower(value):
217
"""
218
Check if string is lowercase.
219
220
Parameters:
221
value: Input string
222
223
Returns:
224
bool: True if string is lowercase
225
"""
226
227
def upper(value):
228
"""
229
Check if string is uppercase.
230
231
Parameters:
232
value: Input string
233
234
Returns:
235
bool: True if string is uppercase
236
"""
237
```
238
239
### Comparison Tests
240
241
Tests for comparing values using various comparison operators.
242
243
```python { .api }
244
def equalto(value, other):
245
"""
246
Check if values are equal (also available as '==' and 'eq').
247
248
Parameters:
249
value: First value
250
other: Second value
251
252
Returns:
253
bool: True if values are equal
254
"""
255
256
def ne(value, other):
257
"""
258
Check if values are not equal (also available as '!=').
259
260
Parameters:
261
value: First value
262
other: Second value
263
264
Returns:
265
bool: True if values are not equal
266
"""
267
268
def greaterthan(value, other):
269
"""
270
Check if value is greater than other (also available as '>' and 'gt').
271
272
Parameters:
273
value: First value
274
other: Second value
275
276
Returns:
277
bool: True if value > other
278
"""
279
280
def ge(value, other):
281
"""
282
Check if value is greater than or equal to other (also available as '>=').
283
284
Parameters:
285
value: First value
286
other: Second value
287
288
Returns:
289
bool: True if value >= other
290
"""
291
292
def lessthan(value, other):
293
"""
294
Check if value is less than other (also available as '<' and 'lt').
295
296
Parameters:
297
value: First value
298
other: Second value
299
300
Returns:
301
bool: True if value < other
302
"""
303
304
def le(value, other):
305
"""
306
Check if value is less than or equal to other (also available as '<=').
307
308
Parameters:
309
value: First value
310
other: Second value
311
312
Returns:
313
bool: True if value <= other
314
"""
315
316
def sameas(value, other):
317
"""
318
Check if values are the same object (identity test).
319
320
Parameters:
321
value: First value
322
other: Second value
323
324
Returns:
325
bool: True if values are same object
326
"""
327
328
def in_test(value, seq):
329
"""
330
Check if value is in sequence (available as 'in' test).
331
332
Parameters:
333
value: Value to search for
334
seq: Sequence to search in
335
336
Returns:
337
bool: True if value is in sequence
338
"""
339
```
340
341
### Meta Tests
342
343
Tests for checking the existence of other tests and filters.
344
345
```python { .api }
346
def filter_test(name):
347
"""
348
Check if filter exists.
349
350
Parameters:
351
name: Filter name
352
353
Returns:
354
bool: True if filter exists
355
"""
356
357
def test_test(name):
358
"""
359
Check if test exists.
360
361
Parameters:
362
name: Test name
363
364
Returns:
365
bool: True if test exists
366
"""
367
```
368
369
## Usage Examples
370
371
### Basic Template Usage
372
373
```python
374
# Template content
375
template_str = '''
376
{% if user is defined %}
377
{% if user.age is number and user.age is greaterthan(18) %}
378
Adult user: {{ user.name }}
379
{% elif user.age is number %}
380
Minor user: {{ user.name }}
381
{% else %}
382
User with unknown age: {{ user.name }}
383
{% endif %}
384
{% else %}
385
No user defined
386
{% endif %}
387
388
{% for item in items %}
389
{% if item is string and item is upper %}
390
UPPERCASE: {{ item }}
391
{% elif item is number and item is even %}
392
EVEN NUMBER: {{ item }}
393
{% elif item is iterable %}
394
SEQUENCE: {{ item | join(', ') }}
395
{% endif %}
396
{% endfor %}
397
'''
398
399
from jinja2 import Template
400
template = Template(template_str)
401
402
result = template.render(
403
user={'name': 'Alice', 'age': 25},
404
items=['HELLO', 42, [1, 2, 3], 'world', 17]
405
)
406
```
407
408
### Programmatic Test Usage
409
410
```python
411
from jinja2 import Environment
412
413
env = Environment()
414
415
# Test values programmatically
416
result1 = env.call_test('defined', 'hello') # True
417
result2 = env.call_test('number', 42) # True
418
result3 = env.call_test('even', 42) # True
419
result4 = env.call_test('in', 'hello', ['hello', 'world']) # True
420
```
421
422
### Custom Tests
423
424
Add custom tests to environments:
425
426
```python
427
def is_email(value):
428
"""Test if string looks like an email address."""
429
return isinstance(value, str) and '@' in value and '.' in value
430
431
def is_positive(value):
432
"""Test if number is positive."""
433
try:
434
return float(value) > 0
435
except (ValueError, TypeError):
436
return False
437
438
env = Environment()
439
env.tests['email'] = is_email
440
env.tests['positive'] = is_positive
441
442
# Use in templates: {% if user.email is email %}
443
```
444
445
## Types
446
447
```python { .api }
448
class TestEnvironment:
449
"""
450
Test execution environment providing context and utilities for test functions.
451
452
Attributes:
453
environment: Jinja2 environment instance
454
context: Current template context (if available)
455
eval_ctx: Current evaluation context (if available)
456
"""
457
```