1 # -*- coding: utf-8 -*-
6 Jinja test functions. Used with the "is" operator.
8 :copyright: 2007 by Armin Ronacher.
9 :license: BSD, see LICENSE for more details.
12 from jinja2.runtime import Undefined
15 number_re = re.compile(r'^-?\d+(\.\d+)?$')
16 regex_type = type(number_re)
20 """Return true if the variable is odd."""
25 """Return true if the variable is even."""
29 def test_divisibleby(value, num):
30 """Check if a variable is divisible by a number."""
31 return value % num == 0
34 def test_defined(value):
35 """Return true if the variable is defined:
39 {% if variable is defined %}
40 value of variable: {{ variable }}
42 variable is not defined
45 See the :func:`default` filter for a simple way to set undefined
48 return not isinstance(value, Undefined)
51 def test_undefined(value):
52 """Like :func:`defined` but the other way round."""
53 return isinstance(value, Undefined)
57 """Return true if the variable is none."""
61 def test_lower(value):
62 """Return true if the variable is lowercased."""
63 return unicode(value).islower()
66 def test_upper(value):
67 """Return true if the variable is uppercased."""
68 return unicode(value).isupper()
71 def test_string(value):
72 """Return true if the object is a string."""
73 return isinstance(value, basestring)
76 def test_number(value):
77 """Return true if the variable is a number."""
78 return isinstance(value, (int, long, float, complex))
81 def test_sequence(value):
82 """Return true if the variable is a sequence. Sequences are variables
93 def test_sameas(value, other):
94 """Check if an object points to the same memory address than another
99 {% if foo.attribute is sameas false %}
100 the foo attribute really is the `False` singleton
103 return value is other
106 def test_iterable(value):
107 """Check if it's possible to iterate over an object."""
115 def test_escaped(value):
116 """Check if the value is escaped."""
117 return hasattr(value, '__html__')
123 'divisibleby': test_divisibleby,
124 'defined': test_defined,
125 'undefined': test_undefined,
129 'string': test_string,
130 'number': test_number,
131 'sequence': test_sequence,
132 'iterable': test_iterable,
133 'callable': callable,
134 'sameas': test_sameas,
135 'escaped': test_escaped