7

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 片段或其他东西!

4

3 回答 3

5

我找到了一个可以帮助你的片段。

解析 args 和 kwargs 的标签

于 2013-03-01T11:36:33.100 回答
2

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

from django import template

template.base.token_kwargs(bits,
于 2019-09-03T17:14:13.153 回答
1

要详细说明 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.
    """
于 2021-08-27T09:03:31.653 回答