Using Jinja’s is Test Operator
n
True or False. You use the is operator to apply a test, which is a powerful alternative to writing out full conditional logic in your templates.nn
nn
Basic Syntax
nTo use a test, you place the keyword is after the variable or expression you want to check, followed by the name of the test. The result is a boolean value that you can use in an if statement or other logical operations.nnThe basic syntax is:n
{% if variable is test_name %}n ...n{% endif %}
nFor example, to check if a variable named user_id has been defined in the template context, you would use the defined test:n
{% if user_id is defined %}n <p>Welcome, user with ID: {{ user_id }}</p>n{% else %}n <p>Welcome, guest user!</p>n{% endif %}
nThis is a cleaner way to handle optional data compared to writing if 'user_id' in context.nn
nn
Tests with Arguments
nJust like filters, many tests can accept arguments. If a test only requires a single argument, you can often omit the parentheses for a more natural, English-like syntax.nnFor example, to check if a number is divisible by 3, you can use the divisibleby test:n
{% if loop.index is divisibleby 3 %}n <p>This is the 3rd, 6th, 9th, etc. item.</p>n{% endif %}
nThis is equivalent to the more explicit syntax with parentheses:n
{% if loop.index is divisibleby(3) %}n ...n{% endif %}
nThe ability to omit parentheses for single-argument tests makes your template code more readable. You can use this for a variety of tests, such as checking if a string starts with a certain prefix or if a number is within a specific range.nn
nn
Common Built-in Tests
nJinja includes a variety of built-in tests for common programming scenarios. Here are a few examples:n
- n
defined: Checks if a variable is present in the template context.none: Checks if a variable isNone.string,number,iterable: Check the type of the variable.oddandeven: Check if a number is odd or even.divisibleby(num): Checks if a number is evenly divisible bynum.in: Checks for membership (e.g.,'item' in list).
n
n
n
n
n
n
nThese tests provide a robust set of tools for creating dynamic templates that can adapt to different data types and conditions.nn
nn
Conclusion
nJinja’s is operator, combined with its built-in tests, provides a simple yet powerful mechanism for performing conditional logic in templates. They allow you to write expressive and readable code that cleanly separates presentation from complex application logic. By using tests like is defined or is divisibleby, you can make your templates more robust and responsive to the data they receive.nn
n
