Back to HTML Let's use what we learnt to add a menu

Introduction to Templates

One of the neat features of flask is the ability to add placeholders to your templates that can contain text from another source.

They’re far simpler to add than many people realise.

Let’s open our index.html file from our template folder and our routes.py file in VSCode.

Let’s modify our index.html file to include some placeholders. They are marked by two curly braces around them: “{{ this }}” is a placeholder. Change the <title> and <h1> tags to be as below.

<html>

    <!--Page attributes-->

    <head>

        <!--Page Title-->

        <title>{{ title }} - Website</title>

    </head>

    <!--Page content-->

    <body>

        <h1>{{ title }}</h1>

        <p>Welcome to a webpage that's not on the web</p>

    </body>

</html>

We haven’t told it what to put in those placeholders yet. Let’s change the routes file now.

from flask import render_template #imports the ability to render HTML files

from app import app #import statement for the whole application instance

 

@app.route('/'

@app.route('/index'#these are called decorators. They assosiate the URL (or links) of / and /index to this function

def index(): #now the function definition

    return render_template('index.html'title='Home'#MODIFIED #renders the HTML file we created, with the placeholder “title” replaced with “Home”

Now let’s run flask and see the result.

You’ll see that where there’s a placeholder, the text has been replaced by “Home”.

We can now create different pages from the one HTML template we created.

Let’s add this statement to the end of our routes.py file:

@app.route('/other')

def other():

    return render_template('index.html'title='Other')

Now let’s run Flask again, but this time let’s navigate to “localhost:5000/other”. You’ll see that the structure has remained the same but the text has changed.

If we go back to “localhost:5000/” or “localhost:5000/index” we’ll see that the same structure is used for both but the placeholders are replaced by other text.

Back to HTML Return to top Let's use what we learnt to add a menu