开发者

django: passing custom tag a parameter

开发者 https://www.devze.com 2023-02-14 21:51 出处:网络
I\'m trying to pass a variable from the URL (not the query string) to a custom tag, but it looks like I\'m getting a ValueError when converting it to an int.It appears at first glance that it\'s comin

I'm trying to pass a variable from the URL (not the query string) to a custom tag, but it looks like I'm getting a ValueError when converting it to an int. It appears at first glance that it's coming in as a string like "project.id" instead of the actual integer value of that. From what I understand, the tag parameters are always strings. If I print out the value of the parameter in my view before sending it down, it appears correct. It might just be a string, but I figured that shouldn't matter if the template is going to convert it to an int anyway, right?

# 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 ar开发者_StackOverflow中文版gument" % token.contents.split()[0]
    print(projectId)
    projectId = int(projectId)

    return ProposalHtmlNode(int(projectId))

class ProposalHtmlNode(template.Node):
    def __init__(self, projectId):
    self.projectId = projectId


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 of template.Variable and then resolve it in the Node's render 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 the simple_tag decorator, which as well as not needing a separate Node also gets the variables already resolved as its parameters.

0

精彩评论

暂无评论...
验证码 换一张
取 消