【发布时间】:2023-03-24 17:33:01
【问题描述】:
我正在尝试将变量从 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
【问题讨论】:
标签: python django templatetag