DarkSuniuM
DarkSuniuM

Reputation: 2592

Django Use Static files URL in Static Files

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' %}

Is there other way to do this?

Both font and style.css are served as Static

Upvotes: 1

Views: 1953

Answers (1)

Serafeim
Serafeim

Reputation: 15104

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 %}.

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:

The Django-template-stylesheet named pdfstylefonts.css in the templates directory:

{% load static %}
@font-face {
    font-family: "Calibri";
    src: url({% static "fonts/calibri.ttf" %});
}

And the html template:

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

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" %}'/>).

Upvotes: 1

Related Questions