开发者

Django custom template tag which accepts a boolean parameter

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 %}

<开发者_JAVA技巧!-- Works OK, but is there a better option? -->
{% some_tag "foobar" 0 %}


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',
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜