4👍
✅
You can pass any number of variables to your custom template tag by using Python’s built in way of passing in multiple values from a list. Example:
from django import template
register = template.Library()
@register.tag('my_tag')
def do_whatever(parser, token):
bits = token.contents.split()
"""
Pass all of the arguments defined in the template tag except the first one,
which will be the name of the template tag itself.
Example: {% do_whatever arg1 arg2 arg3 %}
*bits[1:] would be: [arg1, arg2, arg3]
"""
return MyTemplateNode(*bits[1:])
class MyTemplateNode(template.Node):
def __init__(self, *args, **kwargs):
do_something()
def render(self, context):
do_something_else()
Hope that helps you out.
0👍
The easiest way to achieve this is to just use Python’s normal way of accepting a variable number of args:
@register.simple_tag()
def my_tag(*args):
# do stuff with args, which is a list of all the arguments
return 'what you want to output'
Then you can use it like you wanted:
{% my_tag arg1 arg2 arg3 %}
- [Django]-Django forms custom validation on two fields one or the other
- [Django]-Crontab is running but still not executing command Django
- [Django]-Django Social Auth w/ Twitter: HTTP 401 Error (Unauthorized)
Source:stackexchange.com