If you want something available in the template, then yes, making it
available through the context provided in the view is the way to do
it. The various built-in template tags which can add variables to the
context all have limited scope, and in many cases (e.g., the "with"
tag) this is explicit.
> I never suspected this behaviour and got no inkling to expect it from
> the Django docs. Can anyone with more knowledge of the guts of the
> template rendering system suggest why this happens and if there is any
> way to force variables bound by custom tags into the "global scope"?
The answer is that the template context is not a dictionary. It's a
stack of dictionaries, with fall-through lookup semantics.
Various operations going on in the template push a new dictionary onto
the context stack and populate it, then pop that dictionary off the
context stack when they're done. In general, this is a good thing; for
example, it means it's much easier to have tags do whatever they want
without trampling all over each other's context variables. Many
built-in tags take good advantage of this.
If you truly need a way to make a variable available everywhere in a
template, but it's simply not possible to provide that directly
through the initial context, you want to look at the "dicts" attribute
of the Context instance, which is a list of dictionaries. The last one
in the list (e.g., index -1) is the one that originally came from
instantiating the Context with its initial set of variables, and
during normal template use it will always persist for the life of the
rendering process (someone who wanted to shoot themselves in the foot
could write a tag which manually removes it, but the normal context
push/pop operations will not do this and will raise an exception if
you try to pop the last dictionary out of the stack).
--
"Bureaucrat Conrad, you are technically correct -- the best kind of correct."
> Variables you bind within the template itself don't seem to behave
> this way.
>
> Instead they are scoped. If a variable is bound inside a block tag,
> the binding is only valid within that block. I didn't do enough
> experiments yet to tell you how it behaves with nested blocks.
>
I rely on scoping for my templated menus - I do the following in child
templates to mark a menu item current -
In projects_base.html.djt, say:
{% extends "base.html.djt" %}
{% block menubar0_projects %}
{% with 1 as current %}
{{ block.super }}
{% endwith %}
{% endblock %}
So,it's effectively like the content of the menubar0_projects block in
base.html.djt getting a variable "current" defined. This allows me to
keep all my menu definitions in one template, rather than just
overriding the block wholesale.
I'm a django newbie, maybe there was some other way to do it,
but it works fine.