I’ve created a custom template tag and want to have a helper method in my template.Node but when I call the helper method I get the error,
global name 'prepend_to_some_str' is not defined
Here’s the code that causes the error.
from django import template
from django.template.loader import render_to_string
from easy_maps.models import Address
register = template.Library()
@register.tag
def foo(parser, token):
params = token.split_contents()
return FooNode(params[1])
class FooNode(template.Node):
def __init__(self, some_str):
self.some_str = template.Variable(some_str)
def prepend_to_some_str(some_str):
return "foo" + some_str
def render(self, context):
try:
some_str = self.some_str.resolve(context)
context.update({
'full_str': prepend_to_some_str(some_str),
})
return render_to_string('foo.html', context_instance=context)
except template.VariableDoesNotExist:
return ''
Of course if I move the helper method prepend_to_some_str to the global scope it works just fine as in the code below.
from django import template
from django.template.loader import render_to_string
from easy_maps.models import Address
register = template.Library()
@register.tag
def foo(parser, token):
params = token.split_contents()
return FooNode(params[1])
def prepend_to_some_str(some_str):
return "foo" + some_str
class FooNode(template.Node):
def __init__(self, some_str):
self.some_str = template.Variable(some_str)
def render(self, context):
try:
some_str = self.some_str.resolve(context)
context.update({
'full_str': prepend_to_some_str(some_str),
})
return render_to_string('foo.html', context_instance=context)
except template.VariableDoesNotExist:
return ''
Does anyone know why FooNode is looking for prepend_to_some_str in the global scope instead of the class scope in the code that causes the error?
Thanks.
You should define it with
selfas a first argument and call like:self.prepend_to_some_str(some_str)