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
15 from collections import Mapping as MappingType
18 MappingType = (UserDict.UserDict, UserDict.DictMixin, dict)
20 # nose, nothing here to test
24 number_re = re.compile(r'^-?\d+(\.\d+)?$')
25 regex_type = type(number_re)
29 test_callable = callable
32 return hasattr(x, '__call__')
36 """Return true if the variable is odd."""
41 """Return true if the variable is even."""
45 def test_divisibleby(value, num):
46 """Check if a variable is divisible by a number."""
47 return value % num == 0
50 def test_defined(value):
51 """Return true if the variable is defined:
55 {% if variable is defined %}
56 value of variable: {{ variable }}
58 variable is not defined
61 See the :func:`default` filter for a simple way to set undefined
64 return not isinstance(value, Undefined)
67 def test_undefined(value):
68 """Like :func:`defined` but the other way round."""
69 return isinstance(value, Undefined)
73 """Return true if the variable is none."""
77 def test_lower(value):
78 """Return true if the variable is lowercased."""
79 return unicode(value).islower()
82 def test_upper(value):
83 """Return true if the variable is uppercased."""
84 return unicode(value).isupper()
87 def test_string(value):
88 """Return true if the object is a string."""
89 return isinstance(value, basestring)
92 def test_mapping(value):
93 """Return true if the object is a mapping (dict etc.).
97 return isinstance(value, MappingType)
100 def test_number(value):
101 """Return true if the variable is a number."""
102 return isinstance(value, (int, long, float, complex))
105 def test_sequence(value):
106 """Return true if the variable is a sequence. Sequences are variables
117 def test_sameas(value, other):
118 """Check if an object points to the same memory address than another
121 .. sourcecode:: jinja
123 {% if foo.attribute is sameas false %}
124 the foo attribute really is the `False` singleton
127 return value is other
130 def test_iterable(value):
131 """Check if it's possible to iterate over an object."""
139 def test_escaped(value):
140 """Check if the value is escaped."""
141 return hasattr(value, '__html__')
147 'divisibleby': test_divisibleby,
148 'defined': test_defined,
149 'undefined': test_undefined,
153 'string': test_string,
154 'mapping': test_mapping,
155 'number': test_number,
156 'sequence': test_sequence,
157 'iterable': test_iterable,
158 'callable': test_callable,
159 'sameas': test_sameas,
160 'escaped': test_escaped