Reputation: 549
I need help understanding this. I asked this yesterday: How do I write better template logic with if statements in Django?
This is my view now:
def home(request):
context = {
"ignore_paths": {
"/test1/": False,
"/test2/": False,
"/test3/": False,
"/test4/": False,
"/test5/": False,
"/test6/": False,
}
}
return render(request, "index.html", context)
index.html:
{% if not ignore_paths %}
{% include "includes/sidebar.html" %}
{% endif %}
Why do it not work for me?
Upvotes: 0
Views: 183
Reputation: 43300
It didn't work because you weren't using it in the way it was intended....
Your original question was asking how to exclude that side bar in all templates except for a couple.
The way its intended to work is you include the "ignore_paths"
key in the context of those views that do not need to show it, the value isn't important as long as it equates to true.
i.e I used the ":)"
string since a string with any value will equal true.
The template then does the hard work, since the "ignore_paths" key is missing in the context of those views that do need to show it it will evaluate the if statement successfully and enter it to include the sidebar, see the breakdown of the logic involved here.
ignore_paths is included ignore_paths isn't included
{% if not ignore_paths %} {% if not ignore_paths %}
{% if not True %} {% if not False %}
{% if False %} {% if True %}
Doesn't enter if Does enter if statement
Upvotes: 0
Reputation: 1902
Your ignore_paths
variable is a dictionary. It will always be True
unless the dictionary is empty, so {% if not ignore_paths %}
will always evaluate to False
. What you want is to check each of the your paths in ignore_paths
and if any of them are True
to not show template if I'm reading your other post correctly.
I'd make ignore_paths
a list or set of the paths you don't want to show the sidebar to like:
'ignore_paths': {'/test1/', '/test2/', '/test3/', '/test4/', '/test5/', '/test6/'}
then use any to check if any of the paths are in the request.path
:
hide_sidebar = any(path in request.path for path in ignore_paths)
then in your view:
{% if not hide_sidebar %}
{% include "includes/sidebar.html" %}
{% endif %}
Upvotes: 3