Django variable substituted in template directly but not in custom tag

177 Views Asked by At

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...)

2

There are 2 best solutions below

1
zxzak On

VariableDoesNotExist is thrown in line self.title.resolve(context) because when instanitating template.Variable(title), title does not correspond to an existing variable in the current context. That could mean that in your example title is not "page_title". Check.

0
Marco Sulla On

It seems to work now. I've not changed my code at all. Probably this is caused by the framework I'm using (Splunk).