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:

  1. import math
  2. def is_prime(n):
  3. if n == 2:
  4. return True
  5. for i in range(2, int(math.ceil(math.sqrt(n))) + 1):
  6. if n % i == 0:
  7. return False
  8. return True

You can register it on the template environment by updating thetests dict on the environment:

  1. environment.tests['prime'] = is_prime

A template designer can then use the test like this:

  1. {% if 42 is prime %}
  2. 42 is a prime number
  3. {% else %}
  4. 42 is not a prime number
  5. {% endif %}