2011-03-02 66 views
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 

回答

1

问题在于您没有将变量解析为它们包含的值。如果你在你的方法中加入了一些日志记录,你会发现projectId实际上是字符串"projectId",因为这就是你在模板中引用它的方式。您需要定义这是一个template.Variable的实例,然后在Noderender方法中解析它。见the documentation on resolving variables

但是,取决于您在render中实际执行的操作,您可能会发现完全摆脱Node类并使用simple_tag decorator更容易,而且不需要单独的Node也可以获取变量作为其参数解决。