-1

There are so many td elements with a tag and I want to know that user clicked which element and I want to pass from HTML to the backend and process with the user's selection on the backend.

This is my HTML content:

<a href="/selected" ????><td>{{ options1 }}</td></a>
<a href="/selected"><td>{{ options2 }}</td></a>
<a href="/selected"><td>{{ options3 }}</td></a>
<a href="/selected"><td>{{ options4 }}</td></a>
<a href="/selected"><td>{{ options5 }}</td></a>
<a href="/selected"><td>{{ options6 }}</td></a>

When a user clicked one, I want to send it to the backend:

@app.route('/selected', methods=['GET', 'POST'])
def selected():
selected_option = request.args.get('????')
return render_template("selected.html", selected_option=selected_option)

How can I fill the question marks?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

1 Answers1

1

Having the separate variables for options1, options2, etc probably makes this a hassle for a few reasons:

  • You'll need to manually update the hard-coding of the template to add more options.
  • The URL part of each option, might be different from the link text.

You may wish to define your options in a dictionary:

sections = {'first-option': 'I am the first option',
            'second-option': 'Click me for fun and profit',
            'third-option': 'All flights have been cancelled',
           }

Now on the page which generates your link bar, if you pass that across:

return render_template('some_page.html', SECTIONS=sections)

You can then do something like:

{% for key, value in SECTIONS.items() %}
  <a href="{{url_for('selected', section=key)}}">{{value}}</a>
{% endfor %}

This will automatically generate the correct URLs, which are compatible with the following view function:

@app.route('/selected/<section>')
def selected(section):
    # Assuming the first URL:
    print (section) # 'first-option'
    print (sections[section]) # 'I am the first option'

    return render_template("selected.html", selected_option=section)

You may also wish to have a look at this gist which takes the concept a bit further.

This also uses a context processor to insert that SECTIONS variable into all pages, rather than passing it to the individual render_template functions.

v25
  • 7,096
  • 2
  • 20
  • 36