django:传递自定义标签参数
我正在尝试将变量从 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题很简单,您尚未将变量解析为其包含的值。如果您在方法中添加一些日志记录,您将看到此时
projectId
实际上是字符串"projectId"
,因为这就是您在模板中引用它的方式。您需要将其定义为template.Variable
的实例,然后在Node
的render
方法中解析它。请参阅有关的文档解析变量。但是,根据您在渲染中实际执行的操作,您可能会发现完全摆脱 Node 类并仅使用
simple_tag
装饰器,它也不需要单独的 Node 还获取已解析的变量作为其参数。The issue is simply that you haven't resolved the variables to the values they contain. If you put some logging into your method, you'll see that at that point
projectId
is actually the string"projectId"
, because that's how you referenced it in the template. You need to define this is an instance oftemplate.Variable
and then resolve it in theNode
'srender
method. See the documentation on resolving variables.However, depending on what you're actually doing in
render
, you may find it easier to get rid of the Node class altogether and just use thesimple_tag
decorator, which as well as not needing a separate Node also gets the variables already resolved as its parameters.