Integrating Routing into Our Flask Navbar for the Character Counter App

Posted by

Adding Routing to our Flask Navbar – Character Counter App in Flask

Adding Routing to our Flask Navbar – Character Counter App in Flask

In this tutorial, we will be adding routing to our Flask navbar for our character counter app. Routing is essential for navigating between different pages of our web application. We will create a simple navbar with links to different parts of our character counter app.

Creating our Navbar

First, let’s create a simple navbar using HTML and CSS. Below is an example of a basic navbar with three links:

Setting up Routing in Flask

Now that we have our navbar, we need to set up routing in our Flask app. First, we’ll create routes for each of the links in our navbar. We can do this using the @app.route decorator in Flask.


from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('home.html')

@app.route('/counter')
def counter():
    return render_template('counter.html')

@app.route('/about')
def about():
    return render_template('about.html')
    

Creating HTML templates

Next, we need to create HTML templates for each of our routes. We’ll create a separate HTML file for each route using the render_template method in Flask. Here’s an example of the home.html template:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home</title>
</head>
<body>

    <h1>Welcome to our Character Counter App</h1>
    
    <p>This is the home page of our character counter app. You can navigate to the character counter or about page using the navbar above.</p>

</body>
</html>

    

Linking our Navbar to the Routes

Finally, we need to link our navbar to the routes in our Flask app. We can do this by adding the {{ url_for('route_name')}} function to the href attribute of each link in our navbar. Here’s how it looks like:


<nav>
    <ul>
        <li><a href="{{ url_for('home') }}">Home</a></li>
        <li><a href="{{ url_for('counter') }}">Character Counter</a></li>
        <li><a href="{{ url_for('about') }}">About</a></li>
    </ul>
</nav>

    

By using the {{ url_for('route_name')}} function, we ensure that our links are tied to the correct routes in our Flask app. Now, when a user clicks on a link in the navbar, they will be directed to the respective page in our character counter app.

Conclusion

Adding routing to our navbar is a crucial step in creating a navigable web application. By setting up routes in our Flask app and linking them to our navbar, we can provide a seamless user experience for our character counter app. With this, our character counter app is now fully functional with a polished navbar for easy navigation.