Opened 11 years ago
Closed 11 years ago
#21639 closed Bug (fixed)
RenderContext should override __getitem__
Reported by: | Alex Hill | Owned by: | nobody |
---|---|---|---|
Component: | Template system | Version: | dev |
Severity: | Normal | Keywords: | |
Cc: | Triage Stage: | Accepted | |
Has patch: | yes | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | yes |
Easy pickings: | yes | UI/UX: | no |
Description
From the comments for RenderContext:
Name resolution fails if a variable is not found at the top of the RequestContext stack. Thus, variables are local to a specific template and don't affect the rendering of other templates as they would if they were stored in the normal template context.
In RenderContext, the methods __iter__
, get
, and has_key
are overridden. has_key
is called internally by BaseContext.__contains__
, so "in" works as expected, but get
is not similarly called by __getitem__
, so using get
and using indexing syntax give different results. It seems to me that that's an oversight, and to be consistent with the intention as stated in the comment, __getitem__
should be overridden too.
Example of the wrong/inconsistent behaviour:
>>> from django.template.context import RenderContext >>> c = RenderContext({'fruit': 'banana'}) >>> 'fruit' in c True >>> c.push() {} >>> 'fruit' in c False >>> c.get('fruit') >>> c['fruit'] 'banana'
Change History (4)
comment:1 by , 11 years ago
comment:2 by , 11 years ago
Needs tests: | set |
---|---|
Patch needs improvement: | set |
Triage Stage: | Unreviewed → Accepted |
Hi,
Indeed, this looks like an oversight and your patch looks reasonable.
Can you add some tests for it too?
Thanks.
comment:3 by , 11 years ago
Needs tests: | unset |
---|
Of course, should have been in there to begin with. Done now, see the pull request.
Thanks for looking at this!
Alex
comment:4 by , 11 years ago
Resolution: | → fixed |
---|---|
Status: | new → closed |
Patch at https://github.com/django/django/pull/2096