0

I have a static css file in my django app static directory. I have multiple views running of the same css file, since otherwise there would be A LOT of copy and pasting, but I need just a few things to be different depending on the page I'm currently on.

Is it possible to use the django conditional statements like {% if request.path == ... so on inside the static css file?

Or if not what would be a sensible alternative that would achieve the same result? Because the class header.masthead is used about 10 times in the CSS file and if I had to write a new, let's say, header.mastheadcookiepage and assign the same functionality, and do this for multiple new pages, that would be really annoying.

Maybe it's possible to somehow pass in a variable from my views into the css file as a string, and put that variable into the background image url, so that I could pull a different background image from the server depending on the current view?

Perhaps this is a stupid question and I'm approaching this problem the wrong way, but I'm quite new to web developement, so any help is appreciated!

  • 1
    It's a bad idea to have dynamic CSS files. You should be setting classes appropriately on your HTML dynamically, and write your CSS so it styles different classes differently. That's how you properly style "different states" through CSS. – deceze Apr 22 '20 at 09:49
  • @deceze even when that means a lot of repeated code and a bunch of copy and pasting?:( –  Apr 22 '20 at 09:55
  • 2
    @Rico you can have multiple classes on one element. So have one class with all the "repeated" code so you dont have to repeat it and then other classes that just have the specific bits of "different" css – Craicerjack Apr 22 '20 at 10:03
  • 1
    @Rico deceze and Craicerjack are right - your issue is mainly with learning to properly use css. Remember that the "c" in "css" stands for "cascading". – bruno desthuilliers Apr 22 '20 at 10:18
  • 1
    @craicerjack thank you! Your comment lead me to find the correct way to do it:D –  Apr 22 '20 at 10:20

1 Answers1

0

It's a bit difficult to understand what you want to do here without a code example, but if you haven't already, take a look at the Django template extends functionality.

This will enable you to build your frontend in layers, keeping bits of code (such as js and css) that are common to many individual views in the upper base layer so they don't have to be repeated.

You can also use this to extend from layers that only import the relevant css.

And just as a footnote, take a look at this Stack overflow answer with regards to when its best to use css's background-img vs HTML's <img> tag. With this considered, in general it's easier to stick with <img> tag if you're using django dynamic image files. For example:

<img src="{{ image_url }}" alt="{{ image_description}}">