0
我想从URL(不是查询字符串)传递一个变量到自定义标签,但它看起来像转换为int时,我得到一个ValueError。它乍一看似乎是以“project.id”之类的字符串形式出现的,而不是实际的整数值。据我所知,标签参数总是字符串。如果在发送之前将我的视图中的参数值打印出来,它看起来是正确的。它可能只是一个字符串,但我认为如果模板无论如何要将它转换为int都无关紧要,对吧?django:传递自定义标签的参数
# 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