Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django template: Embed css from file

I'm working on an email template, therefor I would like to embed a css file

<head>
   <style>{{ embed 'css/TEST.css' content here }}</style>
</head>

instead of linking it

<head>
   <link href="{% static 'css/TEST.css' %}" rel="stylesheet" type="text/css">
</head>

Any ideas?

like image 946
T. Christiansen Avatar asked Nov 09 '15 10:11

T. Christiansen


People also ask

How do I link a CSS file to a template?

There are three different ways to link CSS to HTML based on three different types of CSS styles: Inline – uses the style attribute inside an HTML element. Internal – written in the <head> section of an HTML file. External – links an HTML document to an external CSS file.

Where do I put CSS files in Django?

Including CSS in Django Template We 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.

How do I link a CSS file to HTML?

CSS can be added to HTML documents in 3 ways: Inline - by using the style attribute inside HTML elements. Internal - by using a <style> element in the <head> section. External - by using a <link> element to link to an external CSS file.


2 Answers

I guess you could use include

<style>{% include "/static/css/style.css" %}</style>    

https://docs.djangoproject.com/en/1.9/ref/templates/builtins/#include

But it might be better to load the contents of the css file in your view, and put it in the context of your view to send it to the template

like image 163
user1797792 Avatar answered Oct 04 '22 00:10

user1797792


You can use django-compressor package. It will add {% compress %} template tag that can join together bunch of JS or CSS files (or inlined code) and put it into template as new, big file or inlined code. For example to inline one CSS file, you can use:

{% compress css inline %}
    <link href="{% static 'css/TEST.css' %}" rel="stylesheet" type="text/css">
{% endcompress %}

You can add more CSS files into one compress tag, they will be concatenated together and wrapped into one <style>tag.

Check usage examples for more details.

like image 21
GwynBleidD Avatar answered Oct 04 '22 00:10

GwynBleidD