According to this thread on the django-developers list, I can't pass the constant False
as a parameter to a Django template tag because it will be treated as a variable name not a builtin constant.
But if I want to create a template tag takes needs a true/false parameter, what's the the recommended way to create (in Python) and invoke (in a template) that template tag?
I could simply pass 1 or 0 inside the template and it would work OK, but given that Django template authoring shouldn't require computer programming knowledge (e.g. 1==True, 0==False) of template writers, I was wondering if there is a more appropriate way to handle this case.
Example of tag definition and usage:
@register.simple_tag
def some_tag(some_string, some_boolean = True):
if some_boolean:
return some_html()
else
return some_other_html()
<!-- Error! False treated as variable name in Request Context -->
{% some_tag "foobar" False %}
<!-- Works OK, but is there a better option? -->
{% some_tag "foobar" 0 %}
DjangoTemplates engines accept the following OPTIONS : 'autoescape' : a boolean that controls whether HTML autoescaping is enabled. It defaults to True . Only set it to False if you're rendering non-HTML templates!
This tag can be used in two ways: {% extends "base.html" %} (with quotes) uses the literal value "base.html" as the name of the parent template to extend. {% extends variable %} uses the value of variable . If the variable evaluates to a string, Django will use that string as the name of the parent template.
Django Code The template tags are a way of telling Django that here comes something else than plain HTML. The template tags allows us to to do some programming on the server before sending HTML to the client.
I came up against this problem a while ago, and arrived at the conclusion that using 1 and 0 was the simplest solution.
However an idea might be to add a context processor which adds True
and False
to the template context using respective names:
# projectname/appname/context_processors.py
def booleans():
return {
'True': True,
'False': False,
}
Then obviously you would need to add that context processor in your Django settings file:
TEMPLATE_CONTEXT_PROCESSORS += {
'projectname.appname.context_processors.booleans',
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With