首页 文章

由烧瓶复制的jinja2模板中的变量重复

提问于
浏览
0

我尝试使用Flask扫描特定文件夹中的所有文件,并自动构建这些文件的URL链接,所以首先我在Flask中定义了一个应用程序路径:

homepath = os.getcwd()    # the root path of the app
@app.route('/<folder>/')          
def showList(folder):
    folder_abs_path = homepath + '/static/'+folder
    files = os.listdir(folder_abs_path)
    return render_template('blog_list.html', files=files, folderName=folder)

并创建一个jinja2模板,如:

{% extends "base.html" %}
{% block body %}
<div id="main-contents">
  <ul>  
    {% for item in files %}
    <li><a href="{{ folderName +'/'+ item }}"> {{ item }}</a></li>
    {% endfor %}
  </ul>
</div>
{% endblock %}

当烧瓶运行时,我键入:

http://localhost:5000/test/

它确实有效,列出我的测试文件夹中的所有文件(即“file1.md”和“file2.md”),但是当我单击file1.md时它没有为文件保留正确的url链接本地网页,它指向一个网址,如:

http://localhost:5000/test/test/file1.md

我想要的是“http://localhost:5000/test/file1.md ", so why there two " test”文件夹名称?

1 回答

  • 0

    正如@Klaus在评论中所说,您正在为静态文件生成相对路径 . 为避免这种情况,只需使用模板中的url_for()函数进行路径生成:

    {% extends "layouts/main.html" %}
    {% block content %}
    <div id="main-contents">
      <ul>  
        {% for item in files %}
        <li><a href="{{ url_for('static', filename=folderName + '/' + item)}}"> {{ item }}</a></li>
        {% endfor %}
      </ul>
    </div>
    {% endblock %}
    

相关问题