I created a custom tag, that works similarly to a block tag:
@register.tag
def dash(parser, token):
nodelist = parser.parse(('enddash',))
parser.delete_first_token()
args = token.split_contents()
title = args[1]
return DashNode(nodelist, title)
class DashNode(template.Node):
def __init__(self, nodelist, title):
self.nodelist = nodelist
if title[0] in ('"', "'") and title[0] == title[-1]:
self.title = title[1:-1]
else:
self.title = template.Variable(title)
self.tpl = """
<div class="dashboard-body container-fluid main-section-body view-mode" data-role="main">
<div class="dashboard-header clearfix">
<h2>{title}</h2>
</div>
{content}
</div>"""
def render(self, context):
try:
title = self.title.resolve(context)
except AttributeError:
title = self.title
output = self.nodelist.render(context)
new_output = self.tpl.format(content=output, title=title)
return new_output
The tag accepts an argument, that can be a string or a variable. I created it following the official documentation.
Tag works without problem with a string. If I use a variable:
{% dash page_title %}
<!-- blablabla -->
{% enddash %}
a VariableDoesNotExist error is raised. But the variable is correctly expanded if I use it directly in the template.
I'm using Django 1.5.5 (and I'm locked with it...)
VariableDoesNotExist is thrown in line
self.title.resolve(context)because when instanitatingtemplate.Variable(title), title does not correspond to an existing variable in the currentcontext. That could mean that in your exampletitleis not"page_title". Check.