Skip to content

Instantly share code, notes, and snippets.

@jsoa
Created May 6, 2011 17:24
Show Gist options
  • Save jsoa/959372 to your computer and use it in GitHub Desktop.
Save jsoa/959372 to your computer and use it in GitHub Desktop.
Elegant way to parse arguments, keyword arguments and/or return variable for a django template tag
def do_sometag(parser, token):
"""
{% tagname arg1 arg2 arg3 ... with kwg1=v kwg2=v kwg3=v ... as varname %}
"""
argv = token.contents.split()
# get the index of 'as' or the total length of the arguments
a = 'as' in argv and argv.index('as') or len(argv)
# get the index from 'with' to 'as' or the total length of arguments
e = 'with' in argv and argv.index('with') or a
# the path args are from the object to either 'with', 'as' or length of arguments
path_args = argv[1: e]
# extra args are from 'with' to 'as' or to length of arguments
extra_args = argv[e+1: a]
# the varname is the last element of the list if 'as' is present
varname = argv[a:] and argv[a+1] or None
# split the extra args by '=' and make a dict
extra_kwgs = dict([(x.split("=")[0],x.split("=")[1]) for x in extra_args if '=' in x])
# do other processing..
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment