Reputation: 1758
Following the advice here, I have access to the allowed_contributors variable in the template and I can print it out, but using it in any kind of if-else statement doesn't work. It doesn't give me a 500 error, but it acts like it's empty.
The file I'm loading from templatetags:
from django import template
from django.conf import settings
register = template.Library()
@register.simple_tag
def allowed_contributors():
return getattr(settings, "ALLOWED_CONTRIBUTORS", "")
Here's what I've put in the template (not showing the "load" command at the top, but I guess that must be working).
<div class="container">
<h1>Create new project</h1>
<p> {% allowed_contributors %} </p>
{% if "true" in allowed_contributors %}
<p>"true" found in allowed_contributors!</p>
{% endif %}
{% if "false" in allowed_contributors %}
<p>"false" found in allowed_contributors!</p>
{% endif %}
</div>
The HTML output looks like:
<div class="container">
<h1>Create new project</h1>
<p> ('auth', 'false') </p>
</div>
I've tried outputting the allowed_contributors multiple times in case it's being consumed the first time, but it seems to make no difference.
Do I need to reference it in a different way when I'm using it as a condition for an if statement?
If it helps I'm using Django 1.8
EDIT: Neither of the sensible answers provided worked for me, probably due to some other config on this project that I'm not aware of. I've worked around it by using the slightly more involved context_processor solution.
Upvotes: 0
Views: 628
Reputation: 308809
{% allowed_contributors %}
This does not set a value in the context, it just outputs the result of the tag.
To assign the value, do
{% allowed_contributors as contributors %}
Then you can display the value,
{{ contributors }}
and use it in other tags:
{% if "true" in contributors %}
<p>"true" found</p>
{% endif %}
In Django 1.8 and earlier, you can't do {% allowed_contributors as contributors %}
with the simple_tag
decorator. You need to use assignment_tag
instead.
@register.assignment_tag
def allowed_contributors():
return getattr(settings, "ALLOWED_CONTRIBUTORS", "")
Upvotes: 1
Reputation: 867
The same code works for me.
Note: <p> {% allowed_contributors %} </p>
needs to be <p> {{ allowed_contributors }} </p>
Maybe that's throwing off your code?
I see
Create new project
('auth', 'false')
"false" found in allowed_contributors!
Upvotes: 1