1 # -*- coding: utf-8 -*-
6 Jinja test functions. Used with the "is" operator.
8 :copyright: (c) 2010 by the Jinja Team.
9 :license: BSD, see LICENSE for more details.
12 from jinja2
.runtime
import Undefined
13 from jinja2
._compat
import text_type
, string_types
, mapping_types
16 number_re
= re
.compile(r
'^-?\d+(\.\d+)?$')
17 regex_type
= type(number_re
)
20 test_callable
= callable
24 """Return true if the variable is odd."""
29 """Return true if the variable is even."""
33 def test_divisibleby(value
, num
):
34 """Check if a variable is divisible by a number."""
35 return value
% num
== 0
38 def test_defined(value
):
39 """Return true if the variable is defined:
43 {% if variable is defined %}
44 value of variable: {{ variable }}
46 variable is not defined
49 See the :func:`default` filter for a simple way to set undefined
52 return not isinstance(value
, Undefined
)
55 def test_undefined(value
):
56 """Like :func:`defined` but the other way round."""
57 return isinstance(value
, Undefined
)
61 """Return true if the variable is none."""
65 def test_lower(value
):
66 """Return true if the variable is lowercased."""
67 return text_type(value
).islower()
70 def test_upper(value
):
71 """Return true if the variable is uppercased."""
72 return text_type(value
).isupper()
75 def test_string(value
):
76 """Return true if the object is a string."""
77 return isinstance(value
, string_types
)
80 def test_mapping(value
):
81 """Return true if the object is a mapping (dict etc.).
85 return isinstance(value
, mapping_types
)
88 def test_number(value
):
89 """Return true if the variable is a number."""
90 return isinstance(value
, (int, float, complex))
93 def test_sequence(value
):
94 """Return true if the variable is a sequence. Sequences are variables
105 def test_sameas(value
, other
):
106 """Check if an object points to the same memory address than another
109 .. sourcecode:: jinja
111 {% if foo.attribute is sameas false %}
112 the foo attribute really is the `False` singleton
115 return value
is other
118 def test_iterable(value
):
119 """Check if it's possible to iterate over an object."""
127 def test_escaped(value
):
128 """Check if the value is escaped."""
129 return hasattr(value
, '__html__')
135 'divisibleby': test_divisibleby
,
136 'defined': test_defined
,
137 'undefined': test_undefined
,
141 'string': test_string
,
142 'mapping': test_mapping
,
143 'number': test_number
,
144 'sequence': test_sequence
,
145 'iterable': test_iterable
,
146 'callable': test_callable
,
147 'sameas': test_sameas
,
148 'escaped': test_escaped