代码之家  ›  专栏  ›  技术社区  ›  DarkSuniuM Mirko Jelic

Django在静态文件中使用静态文件URL

  •  1
  • DarkSuniuM Mirko Jelic  · 技术社区  · 7 年前

    我想在我的电脑中使用自定义字体 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

    1 回复  |  直到 7 年前
        1
  •  1
  •   Thomas8    7 年前

    为了 {% static %} 为了工作,你需要有一个Django模板;不是静态文件。这实际上是可能的:您可以创建一个名为 djangostyle.css 把它放在你的口袋里 templates 文件夹。在此文件中,您可以使用 {%静态%} {% include %} .

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

    以下是其中的两个相关文件:

    pdfstylefonts.css 模板 目录:

    {% 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>
    

    <style>{% include "pdfstylefonts.css" %}</style> )和一个普通的css文件(包括它通常与 <link rel='stylesheet' href='{% static "pdfstyle.css" %}'/>