Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom template tag args and kwargs parser

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!

like image 567
Yuji 'Tomita' Tomita Avatar asked Feb 16 '13 00:02

Yuji 'Tomita' Tomita


3 Answers

I found a snippet that may be able to help you.

Tag that parses args and kwargs

like image 170
SWilder Avatar answered Sep 22 '22 11:09

SWilder


You can also use this in the new Django.

from django import template

template.base.token_kwargs(bits,
like image 41
Peyman Avatar answered Sep 19 '22 11:09

Peyman


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.
    """
like image 36
run_the_race Avatar answered Sep 20 '22 11:09

run_the_race