What does "resolve_variable" do in Django? ("template.Variable")
Asked Answered
G

3

2

What does resolve_variable do? And could I use it for accessing the request outside of the view?


Edit

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.

Goldoni answered 15/11, 2010 at 10:3 Comment(0)
E
5

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()
Emrick answered 16/11, 2010 at 8:57 Comment(1)
Wow - awesome. Thats cool! I can't know if its completely right but its a great concept. Cheers @EmrickGoldoni
E
1

template.Variable("key.dot.notation").resolve(dict) can get the value from a dictionary with a key dot notation.

For example, you can get name and age from my_dict in test view as shown below:

# "views.py"

from django.http import HttpResponse
from django import template

def test(request):
    my_dict = {'person':{'name':'John','age': 36}}
    name = template.Variable("person.name").resolve(my_dict) # Here
    age = template.Variable("person.age").resolve(my_dict) # Here
    print(name, age) # John 36
    return HttpResponse("Test")

And, you can get the same result as shown below:

# "views.py"

from django.http import HttpResponse
from django import template

def test(request):
    my_dict = {'person':{'name':'John','age': 36}}
    person = template.Variable("person").resolve(my_dict)
    print(person['name'], person['age']) # John 36
    return HttpResponse("Test")

But, if you try to get a value with the key gender which doesn't exist in my_dict as shown below:

# "views.py"

from django.http import HttpResponse
from django import template

def test(request):
    my_dict = {'person':{'name':'John','age': 36}}
    gender = template.Variable("person.gender").resolve(my_dict) # Here
    print(gender)
    return HttpResponse("Test")

Then, you get the error below:

django.template.base.VariableDoesNotExist: Failed lookup for key [gender] in {'name': 'John', 'age': 36}

*You can see the @register.tag's example of Passing template variables to the tag in which template.Variable("key.dot.notation").resolve(dict) is used to get a value from context with a token.

Embosser answered 13/5, 2023 at 20:32 Comment(0)
P
0

what does resolve_variable do

Resolves a variable in a template tag.

could I use it for accessing the request outside of the view

In a template tag? Yes, as long as the request is in the context - but you don't necessarily need resolve_variable for that, if you're using a simple tag or inclusion tag.

Prebend answered 15/11, 2010 at 10:28 Comment(1)
and yes, Variable resolution has changed in the 1.0 release of Django. template.resolve_variable() has been deprecated in favor of a new template.Variable class.Hesketh

© 2022 - 2024 — McMap. All rights reserved.