我正在尝试将 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