简体   繁体   English

Django模板:从文件中嵌入css

[英]Django template: Embed css from file

I'm working on an email template, therefor I would like to embed a css file 我正在研究一个电子邮件模板,因此我想嵌入一个css文件

<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? 有任何想法吗?

I guess you could use include 我想你可以使用include

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

https://docs.djangoproject.com/en/1.9/ref/templates/builtins/#include 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 但是在视图中加载css文件的内容可能会更好,并将其放在视图的上下文中以将其发送到模板

You can use django-compressor package. 你可以使用django-compressor软件包。 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. 它将添加{% compress %}模板标记,可以将一堆JS或CSS文件(或内联代码)连接在一起,并将其作为新的大文件或内联代码放入模板中。 For example to inline one CSS file, you can use: 例如,为了内联一个CSS文件,您可以使用:

{% 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. 您可以将更多CSS文件添加到一个压缩标记中,它们将连接在一起并包装到一个<style>标记中。

Check usage examples for more details. 查看用法示例以获取更多详细信

On solution would be the use of include: 解决方案是使用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. 您必须在模板目录中放置副本或链接到css文件。 Or you use a hardcoded link as above, which may break in production. 或者您使用上面的硬编码链接,这可能会破坏生产。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM