Calling python functions in HTML file in Flask


Question

I have a list of folders in my python file, and in an HTML file I iterate over the list to display the names of each folder on my page.

{% for folder in folders %}
<li><a href = {{folder}}> {{folder}}</a></li>
{% endfor %}

What I am trying to do is make it so when you click on the folder, it will do the same thing, but inside the clicked folder. I have a function open_folder that takes one parameter (the clicked folder name), but my problem is that I don't really know how to call the function with a parameter in the HTML file. A lot of pages or tutorials I have seen only have the python files. In my main file I also have the route as

/<route>/

I am new to Flask and was just wondering if anybody had examples for how to do this. It would be much appreciated.

1
3
7/21/2012 6:54:29 AM

Accepted Answer

With the assumption that folder is something whose contents you'd want to return dynamically as its own page, the appropriate way to do this would be to have a separate route and view that handles folders. Something like the following:

@app.route("/folder/<folder_name>/")
def folder(folder_name):
    # do something with folder_name
    pass

And in your HTML you would link to it as follows:

<a href="{% url_for('folder', folder_name=folder) %}">{{ folder }}</a>

Obviously you'd want to update the route accordingly, depending on the contents of folder, but that's the "Flask way" of linking to dynamic content.

2
7/21/2012 5:23:28 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon