【问题标题】:Django Use Static files URL in Static FilesDjango 在静态文件中使用静态文件 URL
【发布时间】:2019-03-05 07:36:48
【问题描述】:

我想在 style.css 文件中使用自定义字体,该字体将由 StaticFiles 提供服务

我知道我可以用这样的方式对其进行硬编码:

@font-face {
  font-family:"NotoSansArabic";
  font-style:normal;
  src:
  url("/static/myApp/fonts/NotoSansArabicUI-ExtraBold.ttf") format("truetype")
}

我正在寻找类似的东西:

{% static 'myApp/fonts/NotoSansArabicUI-ExtraBold.ttf' %}

还有其他方法吗?

font 和 style.css 都作为Static

【问题讨论】:

    标签: python django django-templates


    【解决方案1】:

    要让{% static %} 工作,您需要一个 Django 模板;不是静态文件。这实际上是可能的:您可以创建一个名为 djangostyle.css 的文件并将其放入您的 templates 文件夹中。在这个文件中,您可以像往常一样使用{% static %}。然后,在您的模板中,您将使用 {% include %} 引用此文件。

    如果您想查看完整示例,请查看我的 Django PDF 指南文章:https://spapas.github.io/2015/11/27/pdf-in-django/#changing-the-font-to-a-unicode-enabled-one

    这里有两个相关文件:

    templates 目录中名为 pdfstylefonts.css 的 Django 模板样式表:

    {% 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(通过 &lt;style&gt;{% include "pdfstylefonts.css" %}&lt;/style&gt; 包含它)和普通 css 文件(通过&lt;link rel='stylesheet' href='{% static "pdfstyle.css" %}'/&gt; 包含它)之间的区别。

    【讨论】:

    • {% include %} 的坏处是它会将所有样式写入头部,这使得页面加载速度比我们使用外部 css 文件时慢,无论如何,谢谢
    猜你喜欢
    • 2018-11-29
    • 2014-02-26
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-23
    • 2014-11-23
    相关资源
    最近更新 更多