Instead of repeating your HTML code for each template file you can use template inheritance, where templates can inherit from each other and just override parts. We call these overridable parts: Blocks. Once we extended a template, we can assign new values to the blocks of the inheriting template.
{% block content %} Start content block
{% endblock %} End of block
{% extends “layout.html” %} Inherits HTML Document
{{ super() }} A function that inherits extended specific content of an HTML tag
EXERCISE
App
[flask_app.py]: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')
Super Template
[templates/layout.html]:
<!DOCTYPE html> <html> <head> <title>{% block title %} Flask Basics {% endblock %}</title> </head> <body> {% block content %} {% endblock %} <p>Brought to you by the folks at Treehouse!</p> </body> </html>
Requested Template #1
[templates/index.html]:{% extends "layout.html" %} {% block title %} Homepage | {{ super() }} {% endblock %} {% block content %} <h1>Hello from {{ name }}! </h1> {% endblock %}
Requested Template #2
[templates/add.html]:
{% extends "layout.html" %} {% block title %} Adding | {{ super() }} {% endblock %} {% block content %} <h1> {{ num1 }} + {{ num2 }} = {{ num1+num2 }}</h1> {% endblock %}