Search code examples
pythonvariablesflaskroutesclickable

Python, Flask - How do I make clickable links in the templates folder and redirect to a different page?


This is my flask.py file:

names = ["jack", "bob", "sam"]

@app.route('/home')
def home():
    return render_template('home.html', names=names)

@app.route('/name')
def name():
    return render_template('names.html')

and this is my home.html file:

{% for row in names %}
    <a> {{row}} </a>        
{% endfor %}

What I am trying to do is, make each {{row}} tag a clickable link and have it redirect me to the names.html file.

I want the names to have their own unique page and perhaps a way to store the row name that I click in a variable and somehow send it to the flask.py file.


Solution

  • {% for row in names %}
    <a href="name/{{row.name}}"> {{row}} </a>        
     {% endfor %}
    

    Jinja allows for dynamic variable naming which also means dynamic path links.

    So if you wanted each name to take you to a special route you would need to first create a route that will display unique information..

    Now if you want your web server to receive data from the html file you will need to create a route that takes in a POST request and give it the logic as to what to do with the data. Weather that me to redirect to index and pass in the data names=names... etc