Your First Flask Template
A template is a page with blanks to fill in. The render_template_string call fills the blanks.
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__)Render a greeting
The template has one blank, {{ name }}. The call fills it with Ana.
@app.route("/hello")
def hello():
return render_template_string("<h1>Hello {{ name }}!</h1>", name="Ana")Ask for the page
The test client asks for /hello and prints the filled-in page.
client = app.test_client()
print(client.get("/hello").data.decode())Example
from flask import Flask, render_template_string
app = Flask(__name__)
@app.route("/hello")
def hello():
return render_template_string("<h1>Hello {{ name }}!</h1>", name="Ana")
client = app.test_client()
print(client.get("/hello").data.decode())Key points
- A template holds HTML with {{ }} blanks.
- render_template_string fills the blanks with values.
- Pass each value by name, like name="Ana".
- Templates keep the page text out of the view.
In this example, the view renders a template with one blank, {{ name }}. The call fills the blank with Ana. The test client asks for /hello and prints the filled-in page.
Note
Templates use the Jinja language, built into Flask.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What fills the blank {{ name }} in a template?