【问题标题】:django: passing custom tag a parameterdjango:将自定义标签传递给参数
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2014-07-14
      • 1970-01-01
      • 1970-01-01
      • 2014-10-28
      • 2021-09-04
      • 2010-11-15
      • 2010-10-12
      • 2014-08-23
      • 1970-01-01
      相关资源
      最近更新 更多