python - url_for 未在 Flask 中定义

标签 python

import os
from jinja2 import Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader('templates'))
from flask import Flask,url_for
app = Flask(__name__)

@app.route('/')
def hello_world():
    tmpl = env.get_template('index.html')
    sidebar = env.get_template('sidebar.html')
    return tmpl.render(root_url="",sidebar=sidebar.render())

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

在 tempaltes/index.html 中

{{ url_for('static', filename='js/main.js') }}

不过,我得到 url_for 未定义?我正在尝试按照在线示例进行操作,但我不知道为什么会这样

最佳答案

我认为问题是您试图在 jinja html 模板中包含代码逻辑。 Jinja 在设计上禁止这样做,因此代码/表示不会混合。

因此,我建议在代码中生成 url,将其存储在您发送给 jinja 的对象中的某处,然后在模板中使用该变量。类似的东西:

def hello_world():
    tmpl = env.get_template('index.html')
    sidebar = env.get_template('sidebar.html')
    js_url = url_for('static', filename='js/main.js')
    return tmpl.render(root_url="",sidebar=sidebar.render(), jsurl=js_url)

然后在模板端:

<script type="text/javascript" src="{{jsurl}}"></script>

关于python - url_for 未在 Flask 中定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20843085/

相关文章:

.net - 跟踪 Windows API 调用

python - 排除位置以在 python 中创建新间隔

python - 将日期范围行拆分为年(取消分组) - Python Pandas

python - 保证文件关闭

python - 按计数迭代计数器中的项目

python - Django Selenium 单击 ajax 模式弹出窗口上的按钮

python - 如何在 ipad 上使用 python?

python - 在 Windows 中将 EOF 发送到 PyCharm 控制台

python - 使用 python docx 将文本居中

Python 3.3 序列 key 生成器列表问题