3

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.

2
  • It's not clear to me what you mean. I think what you should be doing is making a POST request to a view that takes the folder name. If you want the action of 'open_folder' to occur without making another request you will need to handle it in the browser with Javascript. Commented Jul 21, 2012 at 13:40
  • I think my open_folder method should be called in the post method, but as far as i know you call the post method like method = post and i need post to take a parameter. I think the problem i may be having is the app route with <route> at theend always returns a 404 error, so i dont think I know how to use that correctly. I am trying to figure out a lot so sorry if my explainations arent the best. still new. but thanks for the help Commented Jul 21, 2012 at 17:35

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks! the link actually should be <br> <a href = "{{ url_for(... }}"> <br> instead of {% %}, at least that is what worked for me.
No problem! I believe in Jinja {{ }} is to output values and {% %} is for Python logic, like if statements, loops and function calls. Perhaps they've doubled down to be graceful in case of accidental use of {{ }}.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.