OK, so I've got a template tag and a corresponding Node class. In order to check the value of two template variables in the Node.render method, I'm using the template.Variable class as specified in the docs. However, I'm wondering if there is any point to this, given the extra lines of code that are required to instantiate the class in the Node.__init__ method, then resolve each of the two variables within separate try-except blocks in case of a template.VariableDoesNotExist error. Given that both the variables are Python literals (boolean and list) and context.get('name', default) works as expected without the extra boilerplate, I'm wondering why it's not a documented way of doing this.
In summary, the following types of variable lookup give identical results when dealing with Python literals -- except that using the context directly removes the need for the try-except block and also eliminates the Django template.Variable checking code, which is redundant in this case:
class ExampleNode(template.Node):
def __init__(self):
self.a1 = template.Variable('a_variable')
def render(self, context):
try:
a1 = self.a1.resolve(context)
except template.VariableDoesNotExist:
a1 = False
a2 = context.get('a_variable', False)
I'll add once again that these variables are simply set in a view context as Python literals.
-- You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
For more options, visit https://groups.google.com/groups/opt_out.
No comments:
Post a Comment