Filipe Correia
Filipe Correia

Reputation: 5687

Test the return value of a template tag

There's a boolean variable defined in settings.py that I'd like to make visible in my templates, so that I can control whether a part of the template is shown.

I've thought of creating a template tag to expose the value to the template:

@register.simple_tag
def show_something():
    return settings.SHOW_SOMETHING

... which I would use in the template like this:

{% if show_something %}
    Show it
{% endif %}

... but unfortunately it doesn't seem to work.

Also tried outputting the value, and this displays it as I expected:

{% show_something %}

Any idea if using a template tag is possible for what I need, or if there's a better way?

Upvotes: 1

Views: 205

Answers (1)

Ngenator
Ngenator

Reputation: 11269

I think a template context processor might be better suited for this. Put a context_processors.py file in your project

context_processors.py

from django.conf import settings

def some_setting(request):
    # Or some other logic here instead of always returning it
    return {
        'some_setting': settings.SOME_SETTING
    }

settings.py

SOME_SETTING = False

TEMPLATE_CONTEXT_PROCESSORS = (
    ...,
    'path.to.context_processors.some_setting'
)

and in your templates you can now access the variable with {{ some_setting }} or use it in an if statement like {% if some_setting %}Show this{% endif %}

Upvotes: 2

Related Questions