[Django]-How to get optional parameters for custom template tags in Django?

4👍

simple_tag works as Python invoking similarly.

If your are passing literal True in template, it would be treated as a variable named True and be searched in template context. If there is not True defined, the value becomes '' and coerced to False by Django, as long as the crop field is a models.BooleanField.

For example,

in foo/templatetags/foo.py

from django import template
register = template.Library()

def test(x, y=False, **kwargs):
    return unicode(locals())

in shell

>>> from django.template import Template, Context
>>> t = Template("{% load foo %}{% test 1 True z=42 %}")
>>> print t.render(Context())
{'y': '', 'x': 1, 'kwargs': {'z': 42}}

# you could define True in context
>>> print t.render(Context({'True':True}))
{'y': True, 'x': 1, 'kwargs': {'z': 42}}

# Also you could use other value such as 1 or 'True' which could be coerced to True
>>> t = Template("{% load foo %}{% test 1 1 z=42 %}")
>>> print t.render(Context())
{'y': 1, 'x': 1, 'kwargs': {'z': 42}}
>>> t = Template("{% load foo %}{% test 1 'True' z=42 %}")
>>> print t.render(Context())
{'y': 'True', 'x': 1, 'kwargs': {'z': 42}}
👤okm

Leave a comment