Django template: Embed css from file

倾然丶 夕夏残阳落幕 提交于 2019-12-12 11:36:59

问题


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?


回答1:


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




回答2:


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.




回答3:


On solution would be the use of include:

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

But it is kind of messy! You have to place a copy or link to your css-file in your templates directory. Or you use a hardcoded link as above, which may break in production.



来源:https://stackoverflow.com/questions/33607083/django-template-embed-css-from-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!