Flask Tutorial Using Templates and Jinja2

Flask Tutorial Part 3: Templates and Jinja2 | DarchumsTech

Flask Tutorial Part 3: Using Templates and Jinja2

🧠 What Are Templates in Flask?

Templates let you separate HTML from your Python code. Flask uses Jinja2 as its templating engine to dynamically insert values into HTML pages using special syntax like {{ variable }}.

📁 Template Folder

Create a folder named templates in the root of your Flask project. Flask automatically looks in this folder for HTML files.

✍️ Creating a Template

Create a file hello.html inside the templates folder:

<!DOCTYPE html>
<html>
  <head>
    <title>Hello Page</title>
  </head>
  <body>
    <h1>Hello, {{ name }}!</h1>
  </body>
</html>

🐍 Flask Code to Render the Template

from flask import Flask, render_template

app = Flask(__name__)

@app.route("/<name>")
def hello(name):
    return render_template("hello.html", name=name)

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

🔍 Explanation

  • render_template loads the hello.html file from the templates folder.
  • {{ name }} in the template is replaced by the value passed from the Python route.
  • This makes your web page dynamic and reusable for different values of name.

🚀 Try It Out

Run your Flask app and visit http://localhost:5000/Alex. You should see Hello, Alex! displayed in the browser.

📌 Summary

  • ✅ Flask uses Jinja2 for templating.
  • 📁 Templates go inside a folder named templates.
  • 📌 Use {{ }} to insert dynamic values.

Comments