What does resolve_variable
do? And could I use it for accessing the request
outside of the view?
So template.Variable
is the correct way to go - but I'm still unsure of its purpose. The documentation doesn't really help.
Cheers guys.
I'm assuming your trying to write a custom template tag here, so here's what you do.
In your compilation function, you bind the variable like so:
@register.tag
def my_tag(parser, token):
# This version uses a regular expression to parse tag contents.
try:
# Splitting by None == splitting by spaces.
tag_name, var_name = token.contents.split(None, 1)
except ValueError:
raise template.TemplateSyntaxError, "%r tag requires arguments" % token.contents.split()[0]
#this will "bind" the variable in the template to the actual_var object
actual_var = template.Variable(var_name)
return MyNode(template_variable)
class MyNode(template.Node):
def __init__(self, actual_var):
self.actual_var = actual_var
def render(self, context):
actual_var_value = self.actual_var.resolve(context)
#do something with it
return result
If you only want access the request, you bind against the variable directly in the node. Make sure you have the request in the context:
from django.template import RequestContext
def my_view(request):
#request stuff
return render_to_response("mytemplate.html", {'extra context': None,}, context_instance=RequestContext(request))
Then in your template tag code.
@register.tag
def simple_request_aware_tag(parser, token):
return SimpleRequestAwareNode()
class SimpleRequestAwareNode(template.Node):
def render(self, context):
request = template.Variable('request').resolve(context)
#we want to return the current username for example
return request.user.get_full_name()