
After this lesson, you will be able to:
Don’t you hate it when you have to repeat yourself?
What if you had a website with 10 pages that were almost the same?
Would you code them all from scratch?
index.html PageAny route can use an html page.
my_website.py, set the /randnum/<inte> and / routes to both render_template("index.html").Do we need to rewrite the whole file?
We use templates to:
As well as for one important design reason:
Jinja2 has some really powerful features that web design folks want to take advantage of:
index.htmlWe’ll send a greeting variable into our index.html from both routes.
The routes will display different things!
import render_template?index.html<h1> to be {{ greeting }}.Recognize the {{}}?
In Jinja, templates are rendered with double curly brackets ({{ }}).
Statements are rendered with curly brackets and percent signs ({% %}).
A use case here is passing in logic like:
Let’s change our my_website.py accordingly:
@app.route('/')
def home():
return render_template("index.html", greeting="Hello World!")
...
@app.route('/shownum/<inte>')
def shownum(inte):
my_greeting = "Your number is " + str(inte)
return render_template("index.html", greeting=my_greeting)http://localhost:5000.http://localhost:5000/shownum/26.Do your other routes still work?
What two arguments did we pass into the render_template function?
What’s one reason we use templates?
shakespeare.py.hello.html.
poem in it.hi.txt, then pass that to the hello.html template to display.<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Shakespeare</title>
</head>
<body>
<p>{{text}}</p>
</body>
</html>from flask import Flask, render_template
import os # Note the new import — to be in the file system.
app = Flask(__name__)
file_path = '.'
with open(os.path.join(file_path, 'hi.txt')) as f:
the_text = f.read()
@app.route('/') # When someone goes here...
def home(): # Do this.
return render_template("hello.html", text=the_text)
if __name__ == '__main__':
app.run(debug=True)