I am trying to create a dynamic CSS file using the Django templating engine or any other means.
Currently, I have a CSS rule that looks like this:
background-image: url('http://static.example.com/example.png');
Where http://static.example.com
corresponds to the STATIC_URL
variable in Python. Using the Django templating engine, I could theoretically write something like this:
background-image: url('{{ STATIC_URL }}example.png');
My question is, how can I use the Django templating engine (or any other means) to generate CSS dynamically?
The var() function is used to insert the value of a CSS variable. CSS variables have access to the DOM, which means that you can create variables with local or global scope, change the variables with JavaScript, and change the variables based on media queries.
Including CSS in Django TemplateWe need to load the static files by adding the below line of code at the top of the template (. HTML) file. Then, insert the stylesheet in the HTML using link HTML tag. If you are new to the HTML and CSS, you can learn more about adding CSS in HTML code.
To declare a variable in CSS, come up with a name for the variable, then append two hyphens (–) as the prefix. The element here refers to any valid HTML element that has access to this CSS file. The variable name is bg-color , and two hyphens are appended.
Using CSS variables doesn't require any significant changes in existing stylesheets or new tools and can be easily applied to old projects. Instead of having a hex color code written down in hundreds of places in a file, you can have it defined in just one place – with a CSS variable.
A very good solution here is to use django-compressor. Firstly, if you are serving more than one CSS file, compressor is going to help improve page load times by dropping the number of requests.
A side effect of compressing / concatenating files is that compressor rewrites urls in the css file, so relatively referenced static files (e.g. ../img/logo.png) automatically become fully qualified urls, with the static file url (e.g. http://static.example.com/img/logo.png).
Alternatively you can write custom filters to achieve what you want, or, you can compress your completely static CSS, and some dynamic portions into a single file (for e.g. do this in your base layout file):
{% compress css %}
<link .... />
<style>
.some_rule {background-image:{{MEDIA_URL}}/img/logo.png}
</style>
{% endcompress %}
This also means you don't have to worry about efficiency, as the css/js files are generated on first access of a template which uses them, and they are stored as plain files in your static directory (this is configurable), so they are served as normal, static files.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With