Back to creating a menu | Let’s encrypt with SSL |
Conditional (if) statements
It’s easy to forget to pass a value to the placeholders. Let’s see what happens if we do.
Open the index.html file and modify it so that the <p></p> tags contain a placeholder instead of text.
<!--Tells the program that the main bit of HTML is in the base.html file-->
{% extends "base.html" %}
<!--The content to fit in the block defines in base.html-->
{% block content %}
<h1>{{ title }}</h1>
<p>{{ content }}</p><!--Changed text to a placeholder-->
{% endblock %}
When we run flask we’ll see that we’ve lost the content inside the <p></p> tags

Now let’s look at how we could display an error message if that happened, or even some other content:
We would probably make use of a if statement, that we can add to the HTML code. Note that this if statement won't work if the webpage is started outside of the flask web-server program.
A full if/else statement is visible below. The "x" in the second line will need to be replaced with an condition that needs fulfilled. A full example is then below it.
<!--Condition (this one checks if an object called x has been passed)-->
{% if x %}
<!--Do something-->>
{% else %}
<!--Do something else-->>
{% endif %}
So let’s create an if statement in the index.html file that checks that content is passed to the page. Replace all the text in it with the following code.
<!--Tells the program that the main bit of HTML is in the base.html file-->
{% extends "base.html" %}
<!--The content to fit in the block defines in base.html-->
{% block content %}
<h1>{{ title }}</h1>
{% if content %}
<p>{{ content }}</p>
{% else %}
<p>No content available</p>
{% endif %}
{% endblock %}
Now we receive a message telling us that we forgot to pass some content.

To add content we'll pass it as a parameter. We mention the namespace and then set the content.
We have a title and content namespace that we can fill.
from flask import render_template
from app import app
@app.route('/')
@app.route('/index')
def index():
return render_template('index.html', title='Home', content='This is a home page')
@app.route('/other')
def other():
return render_template('index.html', title='Other', content='This is another page')
You’ll notice that we’re now passing an extra variable called content. When we run the program now, our pages should display the content that we passed from the routes file


Back to creating a menu | Return to top | Let’s encrypt with SSL |