1

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

0

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

The bad thing about {% include %} is it will write all the styles in the head which make page loading slower than when we are using an external css file, anyway, thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.