Django: which context belongs to which template

401 Views Asked by At

I'm on the verge of testing attributes in response.context with django's own test client (in django.test.client).

I get back 5 response.context's. As it seems one for each template part, because when I remove a nested template part (e.g: {% include "sometemplate.html" %}) from the base template the amount of returned context's decreases.

The variables passed to template renderer are in response.context[0].dicts[0]

Is the name of the rendered template stored in the context object somewhere?

1

There are 1 best solutions below

1
On BEST ANSWER

No. The context (which is basically an array of dicts) is passed to the template engine along with the name of the template. Although it is possible to set a context value containing the template name from inside the template, that doesn't happen automatically.

In looking at the code in django/template/loader_tags.py, I noticed that class BlockNode does a context.push() before rendering its contents and a context.pop() afterward. This would preclude setting values inside of one block replacement and then using that value inside of another block replacement. This doesn't come up too often since the Django template language does not directly support value assignment other than by using the {% with %} tag (which, interestingly enough, does the same push/pop as the {% block %} tag).

class IncludeNode subclasses class Node, but not class BlockNode so there doesn't appear to be any nesting of contexts going on in that case.