【问题标题】:Custom template tag args and kwargs parser自定义模板标签 args 和 kwargs 解析器
【发布时间】:2013-02-01 01:21:58
【问题描述】:

Django 附带了一些用于制作自定义模板标签的好工具。

注册 simple_tag 和 assignment_tag 都解析传入的令牌内容并将它们转换为 args, kwargs 正确解析为它们的引用(比如传入了一个变量)。

有没有一种简单的方法可以将此行为添加到常规标记中?

我需要使用parser 对象,所以我需要使用常规标签,但似乎我正在费力地编写大量代码来重现args, kwargs 解析器。

@register.tag(name='snippet')
def snippet_with_defaults(parser, token):
    bits = token.split_contents()[1:]
    bits # bits needs to be converted to args, kwargs easily

我需要一个这样的标签:

{% snippet foo=bar bar=baz %}
This is a glorious django template tag!
{% endsnippet %}

这似乎是一个常见的问题(用于标记参数的 args、kwargs 解析器),它应该有一个 django sn-p 或其他东西!

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    我找到了一个可以帮助你的 sn-p。

    Tag that parses args and kwargs

    【讨论】:

    • 不用担心。很高兴我能帮助你。希望这已经回答了您的问题。
    • 我还没有机会测试它,但我会接受假设它有效!
    【解决方案2】:

    你也可以在新的 Django 中使用它。

    from django import template
    
    template.base.token_kwargs(bits,
    

    【讨论】:

      【解决方案3】:

      详细说明 Peyman 的答案,它使用了 Django 内置的 token_kwargs 函数:

      from django.template.base import token_kwargs
      
      def do_foo(parser, token):
          tag_name, *bits = token.contents.split()
          arguments = token_kwargs(bits, parser)
      

      token_kwargs 的文档字符串:

      def token_kwargs(bits, parser, support_legacy=False):
          """
          Parse token keyword arguments and return a dictionary of the arguments
          retrieved from the ``bits`` token list.
      
          `bits` is a list containing the remainder of the token (split by spaces)
          that is to be checked for arguments. Valid arguments are removed from this
          list.
      
          `support_legacy` - if True, the legacy format ``1 as foo`` is accepted.
          Otherwise, only the standard ``foo=1`` format is allowed.
      
          There is no requirement for all remaining token ``bits`` to be keyword
          arguments, so return the dictionary as soon as an invalid argument format
          is reached.
          """
      

      【讨论】:

        猜你喜欢
        • 2015-01-20
        • 2013-09-25
        • 1970-01-01
        • 2021-07-26
        • 2010-11-15
        • 1970-01-01
        • 1970-01-01
        • 2021-07-13
        相关资源
        最近更新 更多