Using Python Variables in Jinja Templates for Flask

Using Python Variables in Jinja Templates for Flask

7/9/2017


Introduction

Flask is a powerful micro-framework for Python that is used to make web sites (like this one!). Flask utilizes Jinja2 as a template engine which makes it really easy to pass variables created in your Python code straight to your html files.

This post will outline how that process works and can also serve as a nice entry point into using Flask. So, if you've never made a website before, this is a good starting point! To follow along with the code below, be sure you have Flask installed on your machine (pip install flask).


How it's done

This example is going to generate a random number between 1 and 6 to simulate a dice roll inside of Python, pass that value to an html file, and then display it on the webpage. To start off, this is how you want your directory structure to look.

  • dice_roll_example
    • templates
      • random_int.html
    • main.py

So you only need two files. You have a main python file which is going to be the driver of the website and the html file which is going to display the information that's calculated in the python code.


Python code

Here's what main.py looks like.


from flask import Flask, render_template
import random

app = Flask(__name__)

@app.route('/')
def dice_roll():
    dice_roll = random.randint(1, 6)

    return render_template('random_int.html', dice_roll=dice_roll)


if __name__ == '__main__':
        app.run(debug=True)
      

If you've used Flask before, this should look very familiar. If you haven't, here are some of the basic ideas: The @app.route('/') essentially defines our home page. If I made that @app.route('/my_example/') then this code would be displayed on the URL of www.mysite.com/my_example/. Since I left it at just a slash, this is basically the landing page of the site: www.mysite.com.

Next the random number is calculated, then we call a function called render_template(). This function takes an html file that will be rendered, and then any variables that you want to use inside the template. The left side of the equal sign is the name of the variable that you're using from the Python code, and the right hand side is the name you will use to reference it from the html file.


HTML code

Next, I'll show the HTML code that is used to display the value from main.py.


<html>
  <h1>Dice roll!</h1>
  <p>You rolled a {{ dice_roll }}!</p>
</html>
       

Pretty easy right? The syntax to access the variable is {{ var_name }}. That's all you need for a functioning site! You can run this by either opening up the command prompt, changing directory to wherever your main.py file is, and running python main.py, or you can just run the script through whatever IDE you use.

Then, you can open up 'localhost:5000' in your web browser and you should see a page like this:


If statements inside of Jinja templates

Now that we have the basics down, it's time to show some more interesting parts of the Jinja templating. We can simulate a beat the dealer game, utilizing if statements inside of the Jinja template. Basically, we just need to generate one more random variable, and then compare the two numbers in the html file. If the player rolls higher than the dealer they win!

Here's what the Python code would look like:


from flask import Flask, render_template
import random

app = Flask(__name__)

@app.route('/')
def dice_roll():
    dice_roll = random.randint(1, 6)
    dealer_roll = random.randint(1, 6)

    return render_template('random_int.html', dice_roll=dice_roll,
                           dealer_roll=dealer_roll)


if __name__ == '__main__':
        app.run(debug=True)
      

Now, here's how the comparison would work in random_int.html:


<html>
  <h1>Beat the Dealer!</h1>
  <p>You rolled a {{ dice_roll }}.</p>
  <p>The dealer rolled a {{ dealer_roll }}.</p>
  {% if dice_roll > dealer_roll %}
    <p>You won!</p>
  {% else %}
    <p>You lost!</p>
  {% endif %}
</html>

You can see that in Jinja, if statements are wrapped in {% %} and also require and endif block to close out the if statement. Jinja has all of the normal equality operators that can be used in the if statements.

Here's what the site looks like now! You can refresh to play a new round.

Hopefully that helped serve as an intro to the Flask micro framework for Python, as well as show off some of the powerful features of Jinja templates. Thanks for reading and feel free to leave any comments or questions below!

Check out more posts in the Python category!