🎓 A1Learner
🔍
0 of 50 lessons completed

Flask Template Variables

A template variable is a value shown in a page. The {{ }} marks say where each value goes.

Make the app

This line imports Flask and render_template_string together. The route below renders a template.

from flask import Flask, render_template_string

app = Flask(__name__)

Show a name and a score

The template has two blanks. The call fills name with Ana and score with 9.

@app.route("/card")
def card():
    return render_template_string("<p>{{ name }} scored {{ score }}.</p>", name="Ana", score=9)

Ask for the page

The test client asks for /card and prints the page with both values filled in.

client = app.test_client()
print(client.get("/card").data.decode())

Example

from flask import Flask, render_template_string

app = Flask(__name__)

@app.route("/card")
def card():
    return render_template_string("<p>{{ name }} scored {{ score }}.</p>", name="Ana", score=9)

client = app.test_client()
print(client.get("/card").data.decode())

Key points

  • {{ name }} shows the value of name.
  • Pass every value the template uses.
  • Numbers work in {{ }} like words do.
  • A missing value shows nothing.

In this example, the template has two blanks, {{ name }} and {{ score }}. The call fills them with Ana and 9. The test client asks for /card and prints the filled-in page.

Note

Values pass by name, so order does not matter.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does {{ score }} show when the call passes score=9?