Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 烧瓶中未定义的url__Python - Fatal编程技术网

Python 烧瓶中未定义的url_

Python 烧瓶中未定义的url_,python,Python,在tempaltes/index.html中 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_tem

在tempaltes/index.html中

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)

但是,我得到的url_没有定义?我试图在网上学习这些示例,但我不知道为什么会得到这样的结果,我认为问题在于您试图在jinja html模板中包含代码逻辑。Jinja在设计上禁止这样做,这样代码/表示就不会混合

因此,我建议在代码中生成url,将其存储在发送给jinja的对象中的某个位置,然后在模板中使用该变量。大致如下:

{{ url_for('static', filename='js/main.js') }}
然后在模板端:


您似乎在以一种不推荐的方式使用Flask和Jinja。我建议您使用
render_template
,它还可以为添加对Flask特定函数(如
url_)的访问:

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)

我有一个坏的安装或者什么!是的,我没有看到代码在jinja模板中。当然,该代码在那里不起作用。您可以在代码中生成url,然后将其作为呈现对象的一部分传递。在模板中,你可以有如下内容:
你介意我为这个问题添加一个答案并获得一些信任吗?你使用的Jinja模板有点非标准。Flask本身会自动为Jinja创建环境,当使用Flask的
render\u template()
函数时,您会得到
url\u的
支持。
from flask import Flask, render_template
app = Flask(__name__)

@app.route('/')
def hello_world():
    return render_template('index.html')

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