Django ships with some great tools for making custom template tags.
Register simple_tag and assignment_tag both parse the incoming token contents and convert them to args, kwargs
correctly resolved to their references (say a variable was passed in).
Is there a simple way to add this behavior to a regular tag?
I need to use the parser
object so I need to use a regular tag, but it seems like I'm wading through a lot of code to reproduce the args, kwargs
parser.
@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
I need a tag that functions like this:
{% snippet foo=bar bar=baz %}
This is a glorious django template tag!
{% endsnippet %}
It seems like this is such a common issue (an args, kwargs parser for tag arguments) that it should have a django snippet or something!
I found a snippet that may be able to help you.
Tag that parses args and kwargs
You can also use this in the new Django.
from django import template
template.base.token_kwargs(bits,
To elaborate on Peyman's answer, which uses Djangos built in token_kwargs
function:
from django.template.base import token_kwargs
def do_foo(parser, token):
tag_name, *bits = token.contents.split()
arguments = token_kwargs(bits, parser)
The doc string for 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.
"""
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With