0

我正在尝试将 URL(不是查询字符串)中的变量传递给自定义标记,但看起来在将其转换为 int 时出现了 ValueError。乍一看,它是以“project.id”之类的字符串形式出现的,而不是它的实际整数值。据我了解,标签参数始终是字符串。如果我在发送之前打印出视图中的参数值,它看起来是正确的。它可能只是一个字符串,但我认为模板是否要将其转换为 int 并不重要,对吧?

# 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
4

1 回答 1

1

问题只是您没有将变量解析为它们包含的值。如果您将一些日志记录放入您的方法中,您会看到此时projectId实际上是 string "projectId",因为这就是您在模板中引用它的方式。您需要定义 this 是一个实例,template.Variable然后在Node'render方法中解析它。请参阅有关解析变量的文档

但是,根据您在 中实际执行的操作render,您可能会发现完全摆脱 Node 类并只使用simple_tag装饰器更容易,它不需要单独的 Node 也可以获得已经解析为其参数的变量。

于 2011-03-02T19:28:26.507 回答