Dynamically create Links from List in Flask


I am trying to dynamically create a list of links to files in a static folder and failing with nested {{ {{ }} }} that would be logically required.

A Flask server has files in


they are collected in a list with

FileList = []
for path in os.listdir(FileFolderPath):
    if os.path.isfile(os.path.join(FileFolderPath, path)):

the Link is built with

return render_template('list.html', FileList = FileList)

and the Html has this piece

{% for item in FileList %}

<li><a href=" {{url_for('static', filename=' {{item}} ')  }}">{{item}}</a>  </li>

{% endfor %}

which fails as

filename=' {{item}} '

does not give me the url for the link to the file but just a nonsense link to

which has the wrong folder and name. So how can i give the correct folder and place a link to a {{item}} inside a {{ }} used for url_for ?


What if you only use once the jinja2 markdown as it follows:

{% for link in links %}

        <li><a href="/static/{{ link }}">{{ link }}</a>  </li>

{% endfor %}

Another option, but this mainly depends on what you’re trying to accomplish, is adding another route to your app.py

def get_link(page):
    return f'{page}'

and afterwards in your html file:

<li><a href="{{ url_for('get_link', page=link) }}">{{ link }}</a></li>

Also, you might want to consider using the PEP8 naming guidelines > https://peps.python.org/pep-0008/#type-variable-names

Answered By – Mircea Mesesan

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published