django resolve_variable有什么作用?(template.Variable)

Gly*_*ine 1 python django

怎么resolve_variable办?我可以用它来访问request视图的外部吗?


编辑

template.Variable是正确的方法 - 但我仍然不确定它的目的.文档并没有真正帮助.

干杯伙计们.

Tho*_*mas 5

我假设你试图在这里写一个自定义模板标签,所以这就是你做的.

在编译函数中,您可以像这样绑定变量:

@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
Run Code Online (Sandbox Code Playgroud)

如果您只想访问请求,则直接在节点中绑定变量.确保您在上下文中有请求:

from django.template import RequestContext
def my_view(request):
    #request stuff
    return render_to_response("mytemplate.html", {'extra context': None,}, context_instance=RequestContext(request))
Run Code Online (Sandbox Code Playgroud)

然后在你的模板标签代码中.

@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()
Run Code Online (Sandbox Code Playgroud)