Home > Blockchain >  Rendering buttons from variables in Flask
Rendering buttons from variables in Flask

Time:03-24

I am trying to create a page using Flask that has buttons who's names and actions are defined in the python part of the code instead of the HTML part.

A minimum working example of the code would look like this: main.py:

from flask import Flask

def init_app():
    """Construct core Flask application with embedded Dash app."""
    app = Flask(__name__)

    with app.app_context():
        # Import parts of our core Flask app
        import routes
        return(app)

app = init_app()

if __name__ == "__main__":
    app.run(debug = True)

routes.py:

from flask import render_template, redirect, request
from flask import current_app as app

@app.route('/', methods=['GET', 'POST'])
def home():
    if request.method == 'POST':
        print(request.form.get('test_action'))
        print(request.form.get('extra_action'))
    elif request.method == 'GET':
        return render_template('buttons.html', form="form", extra_name = "Extra_Name", extra_action = "extra_action")
    
    return render_template("buttons.html", extra_name = "Extra_Name", extra_action = "extra_action")

and templates/buttons.html

    <form method="post" action="/">
        <h4>button name: TEST</h4>
        <h4>button action: test_action</h4>
        <input type="submit" value="TEST" name="test_action"/>

        <h4>button name: {{extra_name}}</h4>
        <h4>button action: {{extra_action}}</h4>
        <input type="submit" value={{extra_name}} name={{extra_action}}/>

    </form>

which renders like this:

Rendering of the page

main.py is just initialising everything, nothing relevant is happening in it.

In routes.py, a button name and action name are passed to the HTML code. The HTML code is creating two buttons: one using names hardcoded into it, and one using the names taken from Flask. Then routes.py prints what value it gets from each button. For example, when the program is first started, it prints

None
None

and if the TEST button is pressed, it will print

TEST
None

Now, as I understand it, when the Extra_name button is pressed, it should output

None
Extra_name

which is also how it works if I sub in Extra_name and extra_action myself where they should be going in HTML, but instead it gives

None
None

I know that HTML can see what {{extra_name}} and {{extra_action}} are since directly above it renders them as text, thus as far as I can see, substituting the values in the two pieces of code are identical. Therefore I cannot see why one works and the other doesn't.

CodePudding user response:

That's because

<input type="submit" value={{extra_name}} name={{extra_action}}/>

will give you extra_action/ instead of extra_action

You can fix it by using

<input type="submit" value={{extra_name}} name={{extra_action}}></input>

Result:

None
Extra_Name
  • Related