Jump to content

Flask/Templates

From Wikiversity

index.html

[edit | edit source]
<form name="form" method="post" action"" >
    <label for="name">Enter your name:</label>
    <input name="name" type="text">
    <input type="submit" value="Submit">
</form>

main.py

[edit | edit source]
from flask import Flask
from flask import request
from flask import render_template

app = Flask(__name__, static_folder='.', root_path='/home/runner')

@app.route('/', methods=['GET', 'POST'])
def root():
    if request.method == "GET":
        return app.send_static_file('./index.html')
    elif request.method == "POST":
        return render_template('hello.html', name=request.form['name'])
    else:
        return "Unexpected request.method: " + request.method

if __name__ == '__main__':
    app.run(host='0.0.0.0', port='5000')

templates/hello.html

[edit | edit source]
{% if name %}
  <p>Hello {{ name }}!</p>
{% else %}
  <p>Hello world!</p>
{% endif %}

Try It

[edit | edit source]

Copy and paste the code above into one of the following free online development environments or use your own Templates compiler / interpreter / IDE.

References

[edit | edit source]