Custom Tests
Tests work like filters just that there is no way for a test to get accessto the environment or context and that they can’t be chained. The returnvalue of a test should be True or False. The purpose of a test is togive the template designers the possibility to perform type and conformabilitychecks.
Here a simple test that checks if a variable is a prime number:
import math
def is_prime(n):
if n == 2:
return True
for i in range(2, int(math.ceil(math.sqrt(n))) + 1):
if n % i == 0:
return False
return True
You can register it on the template environment by updating thetests
dict on the environment:
environment.tests['prime'] = is_prime
A template designer can then use the test like this:
{% if 42 is prime %}
42 is a prime number
{% else %}
42 is not a prime number
{% endif %}