Flask无法正确加载css

2024-06-02 08:51:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Flask,一切都很顺利,直到我创建了另一个路径,样式表没有加载

样式表在静态文件夹中,但我无法加载它

它适用于回家后第一条路线上的路线,例如("/home" , "/index", "/dashboard")。当它进入辅助路由(例如("/home/first", "/index/first"))时,它会删除样式


Tags: 路径文件夹flask路由homeindex静态样式
2条回答

The most powerful part of Jinja is template inheritance. Template inheritance allows you to build a base “skeleton” template that contains all the common elements of your site and defines blocks that child templates can override.

例如:

<!  base.html  >

{% extends 'bootstrap/base.html' %}

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

{% block content %}
    <!  your child templates will go here  >
{% endblock %}

此基础模板首先从flask-bootstrap继承样式。然后定义指向styles.css文件的链接。所有子模板的内容都将包含在block content中。因此,无论您创建什么样的模板,只要它继承了这个基础模板,您在styles.css中定义的样式将始终适用

调用home()view函数时呈现的子模板(例如index.html)如下所示:

<!  index.html >

{% extends 'base.html' %}

{% block content %}
    <div class="row">
        <div class="col-md-4">
           <!  content  >
        </div>
    </div>
{% endblock %}

您可以使用关键字extends继承基础模板。如前所述,内容将出现在基本模板的block content中,因此必须明确定义

呈现此页面的路径可以如下所示:

# routes.py

from app import app
from flask import render_template

@app.route("/home")
def home():
    return render_template("index.html")

因此,无论您创建什么样的模板,只要您继承了基础模板,您的样式都将应用于其中的每一个模板

阅读template inheritance doc的更多内容

确保该文件扩展了基础文件或任何包含css样式链接的文件

{% extends "template_that_links_to_css.py" %}

相关问题 更多 >