Variables in jinja2 template imported by flask duplicated
<p>I try to use Flask to scan all the file in a specific folder and build the url links to those files automatically, so first I defined a app route in Flask:</p>

<pre><code>homepath = os.getcwd()    # the root path of the app
@app.route('/&lt;folder&gt;/')          
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)
</code></pre>

<p>And create a jinja2 template like:</p>

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

<p>When flask is running,I typed:</p>

<pre><code>http://localhost:5000/test/
</code></pre>

<p>it does work, list all the files in my test folder(which is "file1.md" and "file2.md"), but it doesn't ceate the proper url links for the files, when I clicked the file1.md in the local web page, it directed to a url like:</p>

<pre><code>http://localhost:5000/test/test/file1.md
</code></pre>

<p>What I want is "<a href="http://localhost:5000/test/file1.md" rel="nofollow">http://localhost:5000/test/file1.md</a>", so why there two "test" folder name?</p>

<p>As @Klaus said in the comment, you are generating relative paths for the static files. To avoid that, just use the <a href="http://flask.pocoo.org/docs/0.11/api/#flask.url_for" rel="nofollow">url_for()</a> function in the template for path generating:</p>

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

python templates flask jinja2