Django resolve_variable有什么作用?(模板.变量) [英] What does django resolve_variable do? (template.Variable)
问题描述
resolve_variable
有什么作用?我可以用它来访问视图外部的 request
吗?
What does resolve_variable
do? And could I use it for accessing the request
outside of the view?
所以 template.Variable
是正确的方法-但我仍然不确定其目的.该文档并没有真正的帮助.
So template.Variable
is the correct way to go - but I'm still unsure of its purpose. The documentation doesn't really help.
干杯们.
推荐答案
我假设您尝试在此处编写自定义模板标签,所以这就是您要做的事情.
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()
这篇关于Django resolve_variable有什么作用?(模板.变量)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!