找不到Python烧瓶jinja图像文件

Ber*_*ard 14 python jinja2 flask

新手问题.

我正在使用Flask,一个用于Python的webframe.Flask使用Jinja渲染模板.我不知道哪个版本的Jinja Flask使用,也不知道如何检索Jinja版本或Flask版本.我使用Python 2.7版.

该模板包含css/image目录中的图像.在Firefox浏览器中直接将模板作为文件查看时,此图像可见.

但不是在执行Flask时:

from flask import Flask, render_template
app = Flask(__name__)

@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
    return render_template('Basic.html', name=name)

if __name__ == '__main__':
   app.debug = True
   app.run()
Run Code Online (Sandbox Code Playgroud)

HTML文件的内容:

 <!DOCTYPE HTML>
 <html>
    <body> 

      <!-- variable example begin -->
      {% if name %}
        <h1>Hello {{ name }}!</h1>
      {% else %}
        <h1>Hello World!</h1>
      {% endif %}

      <!-- variable example end -->

     <img src="css/images/icons/resultset_previous.png" width="16" height="16" alt="previous" title="Previous" border="0">

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

模板运行正常,变量示例按预期运行.但是不显示图像.调试返回:"GET /hello/css/images/icons/resultset_previous.png HTTP/1.1"404 -

我按照文档中的建议在VirtualEnv中运行Flask.图像的路径似乎未知.我该如何设置路径?

cod*_*eek 23

对于Flask,您应该将静态文件保存在文件夹"static"下,然后使用url_for函数.让我们说你的项目被称为"myproject"并使用你的例子,它应该看起来像:

myproject/
    app.py
    templates/
    static/
        css/
            images/
                icons/
                    resultset_previous.png
Run Code Online (Sandbox Code Playgroud)

然后在模板中,您可以调用

<img src= {{ url_for('static', filename = 'css/images/icons/resultset_previous.png') }} width="16" height="16" alt="previous" title="Previous" border="0">
Run Code Online (Sandbox Code Playgroud)

另外,要回答关于jinja版本等的问题,请查看此信息

https://github.com/mitsuhiko/flask/blob/master/.travis-lowest-requirements.txt


Mig*_*uel 8

请参阅Flask文档的此部分.

从模板中引用静态文件的正确方法是:

<img src="{{ url_for('static', filename = 'css/images/icons/resultset_previous.png') }}" width="16" height="16" alt="previous" title="Previous" border="0">
Run Code Online (Sandbox Code Playgroud)