Django在静态文件中使用静态文件URL [英] Django Use Static files URL in Static Files
问题描述
我想在我的 style.css
文件中使用一种自定义字体,该字体将由 StaticFiles
I want to use a custom font in my style.css
file that will get served by StaticFiles
我知道我可以用这样的东西进行硬编码:
I know I can hard code it with something like this:
@font-face {
font-family:"NotoSansArabic";
font-style:normal;
src:
url("/static/myApp/fonts/NotoSansArabicUI-ExtraBold.ttf") format("truetype")
}
我正在寻找类似的东西:
Im looking for something like:
{%static'myApp/fonts/NotoSansArabicUI-ExtraBold.ttf'%}
还有其他方法吗?
font和style.css均用作静态
Both font and style.css are served as Static
推荐答案
要使 {%static%}
起作用,您需要一个Django模板;不是静态文件.实际上这是可能的:您可以创建一个名为 djangostyle.css
的文件,并将其放在 templates
文件夹中.在此文件中,您可以照常使用 {%static%}
.然后,您将从模板中使用 {%include%}
引用此文件.
For {% static %}
to work you need to have a Django template; not a static file. This is actually possible: You can create a file named i.e djangostyle.css
and put it in your templates
folder. In this file you can use {% static %}
as normally. Then, from your template you'll refer to this file using {% include %}
.
如果您想查看完整的示例,请查看我的Django PDF指南文章:
If you want to see a full example of this take a look at my Django PDF guide article: https://spapas.github.io/2015/11/27/pdf-in-django/#changing-the-font-to-a-unicode-enabled-one
这是那里的两个相关文件:
Here are the two relevant files from there:
templates
目录中名为 pdfstylefonts.css
的Django模板样式表:
The Django-template-stylesheet named pdfstylefonts.css
in the templates
directory:
{% load static %}
@font-face {
font-family: "Calibri";
src: url({% static "fonts/calibri.ttf" %});
}
和html模板:
{% load static %}
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>
{% include "pdfstylefonts.css" %}
</style>
<link rel='stylesheet' href='{% static "pdfstyle.css" %}'/>
</head>
<body>
<h1>Λίστα βιβλίων</h1>
<img src='{% static "pony.png" %}' />
<table>
<tr>
<th>ID</th><th>Title</th><th>Cover</th>
</tr>
{% for book in books %}
<tr>
<td>{{ book.id }}</td><td>{{ book.title }}</td><td><img src='{{ book.cover.url }}' /></td>
</tr>
{% endfor %}
</table>
</body>
</html>
请注意,css-django-template(通过< style> {%include"pdfstylefonts.css"%}</style>
与< link rel ='stylesheet'href ='{%static"pdfstyle.css"%}'/>
)正常添加.
Notice the difference between the css-django-template (include it through <style>{% include "pdfstylefonts.css" %}</style>
) and a normal css file (include it as normally with <link rel='stylesheet' href='{% static "pdfstyle.css" %}'/>
).
这篇关于Django在静态文件中使用静态文件URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!