2

I'm using Django.
I have a client that needs a white container box to go behind the content on every page of their django website except on the homepage. I'm new to django and so I don't know of any way to do this.

I know that on Wordpress there is an if statement that can do something along the lines of what I'm looking for: ?php is_front_page(); ?

Is there anything in django that can do something similar? I just need a way to add a css class to an element and then exclude that styling from the homepage of the website.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Raechel
  • 21
  • 2

2 Answers2

0

You can dynamically add a css class to an HTML element like this:

You need to send a value to your HTML via context_data dict, let's take an example, I will asumme you are using Class-Based views.

class MyView(TemplateView):
    def get_context_data(self, *args, **kwargs):
        context = super(MyView, self).get_context_data(*args, **kwargs)
        context.update({'add_class': True})
        return context

Then in your template:

...
<div class='someclass {{ if add_class }}someotherclass{{endif}}'></div>
Gocht
  • 9,924
  • 3
  • 42
  • 81
0

This kind of logic belongs to template tags. You can write your own template tag which checks URL of the current page and returns some string which you can then use as a div class to style the div.

Here is a full example. Add following code to e.g. templatetags/helpers.py in one of your apps:

from django import template
register = template.Library()

@register.simple_tag(takes_context=True)
def is_homepage(context):
    if context.request.path == "/":
        return "homepage"
    else:
        return "not_homepage"

Add following code to all your templates, ideally base template you extend in all other templates:

 {% load helpers %}
 ...
 <div class="{% is_homepage %}">
     ...
 </div>
 ...

You can read more about custom template tags here: https://docs.djangoproject.com/en/1.9/howto/custom-template-tags/

ozren1983
  • 1,891
  • 1
  • 16
  • 34