如何在Flask中添加自定义字体?

时间:2020-07-19 06:02:37

标签: html css flask fonts

我有自己的字体,并且已经创建了他们的Webkit,但是无法加载它。

我以前曾在某些Android和桌面应用程序中使用过该字体,但它运行得很好。

我尝试了3种不同的方式,使用同一个app.py文件

app.py

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def start():
    return render_template('index.html')


if __name__ == '__main__':
    app.run(debug=True)

尝试#1

文件夹结构

-static
--css
---stylesheet.css
---myfont.ttf
-templates
--index.html

stylesheet.css

@font-face{
font-family: myfont;
src: ('myfont.ttf');
}
p {font-family:myfont; color:blue}

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<link rel="stylesheet" href="{{url_for('static', filename='css/stylesheet.css')}}" type="text/css"/>
<body>
<p>test</p>
</body>
</html>

尝试#2

文件夹结构

-static
--css
---stylesheet.css
---myfont.ttf
---myfont.eot
---myfont.svg
---myfont.woff
-templates
--index.html

stylesheet.css

@font-face{
font-family: myfont;
src: ('myfont.eot');
src: ('myfont.eot?#iefix') format('embedded-opentype'),
     ('myfont.woff') format('woff'),
     ('myfont.ttf') format('truetype'),
     ('myfont.svg#myfont') format('svg');
}
p {font-family:myfont; color:blue}

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<link rel="stylesheet" href="{{url_for('static', filename='css/stylesheet.css')}}" type="text/css" />
<body>
<p>test</p>
</body>
</html>

尝试#3

文件夹结构

-static
--fonts
---stylesheet.css
---myfont.ttf
---myfont.eot
---myfont.svg
---myfont.woff
-templates
--index.html

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
    <style>
    @font-face{
    font-family: myfont;
    src: {{ url_for('static',filename='fonts/myfont.eot') }};
    src: {{ url_for('static',filename='fonts/myfont.eot?#iefix') }} format('embedded-opentype'),
         {{ url_for('static',filename='fonts/myfont.woff') }} format('woff'),
         {{ url_for('static',filename='fonts/myfont.ttf') }} format('truetype'),
         {{ url_for('static',filename='fonts/myfont.svg#myfont') }} format('svg');
    }
    p {font-family:myfont; color:green}

    </style>
<body>
<p>prueba</p>
</body>
</html>

我也检查了此链接,但结果还是为负

How do you upload a font to your webpage (is the server needed)?

How to add custom font in python-flask?

1 个答案:

答案 0 :(得分:0)

您必须回到根目录,然后为样式表提供目录。

<link rel="stylesheet" href="{{url_for('static', filename='../css/stylesheet.css')}}" type="text/css"/>

为什么要使用这种类型的吸引? 使用这个:

<link rel="stylesheet" href="../css/styesheet.css" type="text/css">