django:传递自定义标签参数

0 投票
1 回答
1807 浏览
提问于 2025-04-16 12:50

我正在尝试从网址中获取一个变量(不是查询字符串),然后传递给一个自定义标签,但我发现当我把它转成整数时出现了一个值错误。乍一看,它好像是以字符串的形式传入的,比如"project.id",而不是实际的整数值。根据我的理解,标签的参数总是字符串。如果我在视图中打印出这个参数的值,然后再传递下去,它看起来是正确的。可能它只是一个字符串,但我觉得这没关系,因为模板最终会把它转换成整数,对吧?

# in urls.py
# (r'^projects/(?P<projectId>[0-9]+)/proposal', proposal_editor),
# projectId sent down in RequestContext as 'projectId'

# in template
# {% proposal_html projectId %}

# in templatetag file
from django import template

register = template.Library()

@register.tag(name="proposal_html")
def do_proposal_html(parser, token):
    try:
        # split_contents() knows not to split quoted strings.
    tagName, projectId = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError, "%r tag requires a single argument" % token.contents.split()[0]
    print(projectId)
    projectId = int(projectId)

    return ProposalHtmlNode(int(projectId))

class ProposalHtmlNode(template.Node):
    def __init__(self, projectId):
    self.projectId = projectId

1 个回答

1

问题很简单,就是你没有把变量的值提取出来。如果你在你的方法里加一些日志记录,你会发现此时的 projectId 实际上是字符串 "projectId",因为你在模板中是这样引用它的。你需要把它定义为 template.Variable 的一个实例,然后在 Noderender 方法中提取出它的值。可以参考关于提取变量的文档

不过,根据你在 render 方法中实际做的事情,你可能会发现直接去掉 Node 类会更简单,只用 simple_tag 装饰器。这样不仅不需要单独的 Node 类,而且变量也会作为参数自动提取出来。

撰写回答