template.Context.update()

Context.update(other_dict) [source]

In addition to push() and pop(), the Context object also defines an update() method. This works like push() but takes a dictionary as an argument and pushes that dictionary onto the stack instead of an empty one.

>>> c = Context()
>>> c['foo'] = 'first level'
>>> c.update({'foo': 'updated'})
{'foo': 'updated'}
>>> c['foo']
'updated'
>>> c.pop()
{'foo': 'updated'}
>>> c['foo']
'first level'

Like push(), you can use update() as a context manager to ensure a matching pop() is called.

>>> c = Context()
>>> c['foo'] = 'first level'
>>> with c.update({'foo': 'second level'}):
...     c['foo']
'second level'
>>> c['foo']
'first level'
New in Django 1.9:

The ability to use update() as a context manager was added.

Using a Context as a stack comes in handy in some custom template tags.

doc_Django
2016-10-09 18:39:45
Comments
Leave a Comment

Please login to continue.