直接在模板中替换Django变量,但不在自定义标记中替换

2024-09-30 00:37:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个自定义标记,其工作方式类似于块标记:

@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 official documentation之后创建了它。你知道吗

标记与字符串一起工作没有问题。如果我使用变量:

{% dash page_title %}
   <!-- blablabla -->
{% enddash %}

出现VariableDoesNotExist错误。但是如果我直接在模板中使用它,变量就被正确地展开了。你知道吗

我使用的是django1.5.5(我被它锁定了……)


Tags: 标记selfdivtokenparseroutputreturntitle
2条回答

VariableDoesNotExist在self.title.resolve(context)行中抛出,因为在实例化template.Variable(title)时,title与当前context中的现有变量不对应。这可能意味着在您的示例中title不是"page_title"。检查。你知道吗

它现在似乎起作用了。我根本没改代码。可能这是由我使用的框架(Splunk)引起的。你知道吗

相关问题 更多 >

    热门问题