如何从呈现的 HTML 模板呈现 JS 模板?

How can I render a JS template from a rendered HTML template?

如果我想通过 Jinja2 生成 JavaScript 代码,而不仅仅是 HTML,我是否坚持保持 JS 代码内联,或者有什么方法可供我参考脚本?

具体来说:

app.py

from flask import Flask, render_template
app = Flask(__name__)
app.config['DEBUG'] = True

@app.route('/')
def index():
    return render_template('index.html', name='Sebastian', color='pink')

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

index.html

<!DOCTYPE html>
<html>
    <head>
        <meta content="utf-8" http-equiv="encoding">
        <script>
            function myEnterFunction() {
                element = document.getElementById("demo");
                element.style.backgroundColor = "{{ color }}";
            }
        </script>
    </head>
    <body>
        <p>Hello {{ name }}</p>
        <div onmouseenter="myEnterFunction()">
            <p>onmouseenter:
                <span id="demo">Mouse over me!</span>
            </p>
        </div>
    </body>
</html>

如果 JavaScript 代码是内联的,这很好用,但是如果我们想保持整洁并引用一个单独的文件怎么办?

<head>
    <meta content="utf-8" http-equiv="encoding">
    <script src="code.js"></script>
</head>

?

可能,这可以通过将 src="code.js" 替换为

来完成
{% render_template('code.js', color=color) %}

在渲染 HTML 模板的同时,你能看到如何渲染 JS 模板吗?

您可以添加生成 JS 的路由。

@app.route('/script.js')
def script():
    return render_template('script.js', color='pink')

并且在 script.js 中,这应该与您的其他模板位于同一文件夹中:

 function myEnterFunction() {
                element = document.getElementById("demo");
                element.style.backgroundColor = "{{ color }}";
            }

在你的 layout.html 中:

<script src="{{url_for('script')}}"></script>

Jinja2 将解析任何包含其语法的文件。