How to get optional parameters for custom template tags in Django?
django, django-1.4, templates
Solution
`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}}
Problem
I just created a custom template tag. ``` from django import template from lea.models import Picture, SizeCache register = template.Library() @register.simple_tag def rpic(picture, width, height, crop=False): return SizeCache.objects.get_or_create(width=width, height=height, picture=picture, crop=crop)[0].image_field.url ``` This works except for the optional parameter crop. The optional parameter can be set, but is ignored by the function and always set to False.