使用 python 和 Flask 更改 CSS

my_*_*ame 1 html css python jinja2 flask

我不想在我的 css 文件中更改 python/Flask/Jinja2 的 css 行,如下所示:

HTML:

<!DOCTYPE  html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>{{ title }}</title>
    <link href="{{ url_for('static', filename='./css/index.css') }}" rel="stylesheet" type="text/css" />
    <link rel="icon" href="{{ url_for('static', filename='./img/icon.png') }}">
</head>
<body>

    <div class="marquee">
        <div class="v-align">
            <p style="font-size:20vh;"><b>{{ text }}</b></p>
        </div>
    </div>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

CSS:

.v-align {
   font-size: 120px;
   position: relative;
   top: 50%;
   -webkit-transform: translateY(-50%);
   -ms-transform: translateY(-50%);
   transform: translateY(-50%);
}

.marquee {
   vertical-align: middle;
   white-space: nowrap;
   overflow: hidden;
   box-sizing: border-box;
   color: "red";
}

.marquee p {
   display: inline-block;
   padding-left: 100%;
   animation: marquee 30s linear infinite;
}
@keyframes marquee {
   0%   { transform: translate(0, 0); }
   100% { transform: translate(-100%, 0); }
}
Run Code Online (Sandbox Code Playgroud)

我想在使用 python 渲染时将 30 替换为任何值。

Python:

return render_template("my_html_file.html", text="this is a test!", animation_time="30s")
Run Code Online (Sandbox Code Playgroud)

似乎不可能在这样的 CSS 文件中制作它:animation: marquee {{ animation_time }} linear infinite; ,但也许我错了。

yas*_*nth 5

从技术上讲,您所做的将不起作用,因为您传递的animation_timeHTML template而不是CSS file. 一种方法是在HTML文件中添加 css。

<!DOCTYPE  html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>{{ title }}</title>
    <link href="{{ url_for('static', filename='./css/index.css') }}" rel="stylesheet" type="text/css" />
    <link rel="icon" href="{{ url_for('static', filename='./img/icon.png') }}">
    <style>
        .marquee p {
            display: inline-block;
            padding-left: 100%;
            animation: marquee {{animation_time}}s linear infinite;
        }
    </style>
</head>
<body>

    <div class="marquee">
        <div class="v-align">
            <p style="font-size:20vh;"><b>{{ text }}</b></p>
        </div>
    </div>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

Python:

return render_template("my_html_file.html", text="this is a test!", animation_time="30")
Run Code Online (Sandbox Code Playgroud)

一般来说,不建议动态生成 css 文件,因为它们大多是静态的,并且首选从 CDN 提供它们。我不确定是否可以将变量注入 css 文件并将其与link标记链接到当前html文件。

如果您确实有上述用例,我建议在 html 文件中使用内联样式。