I just discovered something I did not expect.

Apparently a Django template does not behave like its context is a
single global scope where if you set a new variable using a custom
template tag it can be accessed anywhere subsequently in the template.

Variables you set into the context initially when you make the method
call to render the template do act like you would expect.

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.

This can have a distinct effect in child templates, where apparently
nothing you do outside of a block tag "counts", so you can't put a
variable into the global scope simply by binding it before the block
tags. Let's say you use a custom tag to test whether the currently
logged in user has privilege to edit the document, and this sets a
variable into the context which can be checked to decide whether to
display certain controls. (Not intended as a security measure, just
not to clutter the interface with controls the user can't use anyway).
If you include the tag in one block, the variable can only be accessed
in that block!

I suppose this is easy enough to fix by doing the binding in the view
when the context is first constructed which would probably have been
easier in the first place, but now I'm curious and want to know what's
happening.

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"?

Stephen
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to