template.Context.flatten()

Context.flatten()

Using flatten() method you can get whole Context stack as one dictionary including builtin variables.

1
2
3
4
5
6
>>> c = Context()
>>> c['foo'] = 'first level'
>>> c.update({'bar': 'second level'})
{'bar': 'second level'}
>>> c.flatten()
{'True': True, 'None': None, 'foo': 'first level', 'False': False, 'bar': 'second level'}

A flatten() method is also internally used to make Context objects comparable.

1
2
3
4
5
6
7
8
>>> c1 = Context()
>>> c1['foo'] = 'first level'
>>> c1['bar'] = 'second level'
>>> c2 = Context()
>>> c2.update({'bar': 'second level', 'foo': 'first level'})
{'foo': 'first level', 'bar': 'second level'}
>>> c1 == c2
True

Result from flatten() can be useful in unit tests to compare Context against dict:

1
2
3
4
5
6
7
8
9
10
class ContextTest(unittest.TestCase):
    def test_against_dictionary(self):
        c1 = Context()
        c1['update'] = 'value'
        self.assertEqual(c1.flatten(), {
            'True': True,
            'None': None,
            'False': False,
            'update': 'value',
        })
doc_Django
2025-01-10 15:47:30
Comments
Leave a Comment

Please login to continue.