App Inline HTML

As you saw, Views can print variables. But it also can print HTML code on the web document:

...
@app.route('/add/<int:num1>/<int:num2>')
def add(num1, num2):
  return """
   <!DOCTYPE html>
     <html>
       <head><title>Adding!</title></head>
       <body>
         <h1> {} + {} = {} </h1>
       </body>
   </html>
   """.format(num1, num2, num1+num2)
...

Templates

Views can also render entire HTML templates.
But first you need to apply the following changes to your code:

  1. Create new folder: templates. This is the default folder name that Flask looks for.
  2. Create new .html files: add.html and index.html, and paste your HTML code in it.
  3. Use Flask’s Jinja2 engine to print app variables, using double mustaches {{num1}}
  4. Now, in your app, import render_template from flask
  5. Pass app variables to the View’s template as arguments to the render_template( ) function

Note: It’s better to have the HTML files have the same names of their views/functions in the app.

[index.html]:

<!DOCTYPE html>
<html>
  <head><title>Howdy!</title></head>
  <body>
    <h1> Hello from {{name}} </h1>
  </body>
</html>

[add.html]:

<!DOCTYPE html>
<html>
  <head><title>Adding!</title></head>
  <body>
    <h1> {{num1}} + {{num2}} = {{num1 + num2}} </h1>
  </body>
</html>

[simple_app.py]:

Using render_template( )

from flask import Flask
from flask import render_template

app = Flask(__name__)

@app.route('/')
@app.route('/<name>')
def index(name="Treehouse"):
  return render_template("index.html", name=name)

@app.route('/add/<int:num1>/<int:num2>')
@app.route('/add/<float:num1>/<float:num2>')
def add(num1, num2):
  context = {'num1': num1, 'num2': num2}
  return render_template("add.html", **context)

app.run(debug=True, port=8000, host='0.0.0.0') 

Testing:

Index URL

treehouse-app.com/Bashar

Output:

Hello from Bashar

 

Add URL

treehouse-app.com/add/1/2

Output:

1 + 2 = 3