body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
box-sizing: border-box;
}
header {
background-color: #f2f2f2;
padding: 20px;
text-align: center;
}
main {
padding: 20px;
}
footer {
background-color: #333;
color: #fff;
padding: 20px;
text-align: center;
}
Template Inheritance in Flask
In Flask, template inheritance allows you to define a base template and then extend or override blocks within that template in child templates. This is particularly useful when you have a common layout that is shared across multiple pages of your web application.
Let’s create a simple web app in Flask that counts the number of characters in a given text input using template inheritance.
Character Counter Web App
Character count: {{ count }}
In this example, we first create a base template that will serve as the common layout for all our web pages. We have defined a header, main content area, and footer section. We have also added some basic styling using CSS.
Then, we create a child template that extends the base template and overrides the main content area to include the form for inputting text and displaying the character count.
Now, let’s take a look at the Flask app that handles the character counter functionality and uses the template inheritance feature:
“`python
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route(‘/’)
def index():
return render_template(‘base.html’)
@app.route(‘/count’, methods=[‘POST’])
def count_characters():
text = request.form[‘text’]
count = len(text)
return render_template(‘child.html’, count=count)
if __name__ == ‘__main__’:
app.run(debug=True)
“`
In this Flask app, we define two routes. The first route renders the base template, and the second route handles the form submission to count the characters in the input text and renders the child template with the character count.
By using template inheritance in Flask, we have created a simple but effective character counter web app with a common layout shared across multiple pages. This makes it easier to maintain and update the layout without having to make changes to every individual page. Template inheritance is a powerful feature that can help you create more maintainable and scalable web applications in Flask.