Adding templates to our Flask app

Build a Twitter Analytics App

1 Introduction: Start Here

2 The First Step: Design Your Solution

3 In Which I Rant a Little

4  Design Solution

5 Writing Great Code

6 Writing the Backend Twitter Server

Writing the Code in Small Parts: Part 1, The Basic App

Part 2: Adding a Counter to Exit

Part 3: Adding Language and Retweet Count

Part 4: Organising Our Code

7 Adding the Data to a Database

8 Testing: What and How to Test

8.1 Testing Our Frontend

8.2 Testing Our Backend

9 Displaying our Data using the Flask Webserver

9.1 Introduction to Flask

9.2 Adding templates to our Flask app

9.3 Displaying our Tweets in the Flask Web Server

10 Future Work and Improvements

Let’s add some templates to our code now. Make sure you’ve read the templates section in the Flask quickstart.

We are working with this file. We will be looking at parts of it:

So we are calling the template top_tweets.html. This template inherits from index.html, so lets look at that first.

The block sections are the ones that can be overridden. You see  we have a graphs section for when we add graphs, a general div section and a tweets section.

Let’s look at our actual file, top_tweets.html:

As you can see, we extend index.html, and override the tweets block.

We have a for loop, because as we will see in the next section, we send the tweets as a list, and we loop over each.

The code in the {{ }} blocks is the one replaced by Jinja2 (our template system) with the value we passed in. You will note I am doing a | safe at the end of tweet.

That’s because, by default, Jinja will sanitise the HTML for us. Which is good for most cases.

However, as we will see later, we are using Twitter’s Javascript function to display the tweets, and it doesnt like our sanitised tweets. So normally, you would be very careful when using safe. In this case, however, we know the Tweets came directly from Twitter, so we can assume they are safe (or you can sue Twitter!).

But yeah, be careful using the safe keyword. Never use it with user input.

The main route in our Flask file is fairly simple, so let’s look at a slightly more complicated example,  the trends template file:

This is slightly more complicated in that we for 2 for loops- the first for trends, the second for the tweets. But other than that, it is similar to the last one.

So now that  we have our templates in place, it is time to send them real data. That’s what we’ll do in the next section.