记住 CSS 模板在 flask 中呈现时样式表发生变化

Remember CSS stylesheet change when templates are rendered in flask

我已经使用 HTML 和 外部(静态)CSS 样式表 构建了一个烧瓶应用程序。该应用程序有一个复选框,该复选框控制 CSS 样式表与 JavaScript 处于活动状态。 2 个不同的外部样式表的目的是允许用户在亮(基本)和暗模式之间切换。

以上功能按预期运行。但是,当呈现新模板时,会加载 <header> 中包含 intiial CSS 样式表 的 base.html 文件。

当在 Flask 中呈现新模板时,如何保留 CSS 样式表中的更改?

例子

对于呈现的每个 html 页面,都会扩展 base.html。此文件包含 base-theme.css 文件作为初始 CSS 样式表。

base.html

<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>Application Name</title>
    <meta name="description" content="Application Name">
    <link rel="favorite icon" href="{{ url_for('static', filename='favicon.ico') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='css/base-theme.css') }}" id="stylesheet_toggle">
    <script type="text/javascript" src="{{ url_for('static', filename='js/switch_mode.js') }}"></script>
</head>

<body>
    {% block body %}{% endblock %}
</body>

</html>

选中复选框 (topnav_right_mode_toggle) 时,CSS 样式表从 base-theme.css 更改为 dark-theme.css 和 JavaScript:

switch_mode.js

window.onload = function () {
    const toggle = document.getElementById("topnav_right_mode_toggle");
    const theme = document.getElementById("stylesheet_toggle");

    toggle.addEventListener("click", function () {
        if (theme.getAttribute("href") == "/static/css/base-theme.css") {
            theme.href = "/static/css/dark-theme.css";
        } else {
            theme.href = "/static/css/base-theme.css";
        }
    });
}

到目前为止,还不错...

现在触发了另一个端点,并为此端点呈现了另一个 html 文件。此 html 文件扩展了 base.html,并且由于 base.html 包含 CSS 样式表:base-theme.css,对样式表的更改:dark-theme.css 已撤消.

如何在呈现另一个 html 文件时记住样式表的更改?

您真正需要做的就是存储此信息,以便它在对服务器的请求之间持续存在,因此跨应用的不同页面。

一个巧妙的解决方案是使用浏览器的 localStorage

您可以只将所选主题的位置存储在 localStorage 中并在每次加载页面时检索,例如

window.onload = function () {
    const toggle = document.getElementById("topnav_right_mode_toggle");
    const theme = document.getElementById("stylesheet_toggle");
    const selected = localStorage.getItem("css");
    if (selected !== null) {
      theme.href = selected;
    }

    toggle.addEventListener("click", function () {
        if (theme.getAttribute("href") == "/static/css/base-theme.css") {
            theme.href = "/static/css/dark-theme.css";
        } else {
            theme.href = "/static/css/base-theme.css";
        }
        localStorage.setItem("css", theme.href);
    });
}

我在我的 flask 网站上的做法是将用户选择的主题存储在数据库中,特别是作为“设置”table 中的布尔值,它与“用户”table.

这让我可以利用 Jinja 并在 base.html 模板中简单地做这样的事情:

<html>
<head>
(...)

{% if current_user.settings.dark_theme %}
  <body class="dark_theme">
{% else %}
  <body>
{% endif %}

(...)
</body>
</html>

然后您可以开始使用如下变量设置 css 样式表:

:root {
  --primary-color: #ffffff;
}

.dark_theme {
  --primary-color: #000000;
}
body {
  background-color: var(--primary-color);
}