Templates and Static Files

Back

Loading concept...

🎨 FastAPI Templates & Static Files

The Art Gallery of Your Web App


The Story: Your Web App is Like an Art Gallery

Imagine you’re building an art gallery.

  • The paintings on the walls? Those are your HTML templates β€” the beautiful pages visitors see.
  • The frames, lighting, and decorations? Those are your static files β€” CSS styles, images, and JavaScript.

Without templates, your gallery has no art to show. Without static files, everything looks plain and boring. Together, they make your gallery stunning!


πŸ–ΌοΈ Part 1: Template Rendering

Painting Pictures for Your Visitors

What is Template Rendering?

Think of a template like a coloring book page.

The page has outlines (the structure), but you fill in different colors each time (the data). Same page, different results!

Simple Example:

Hello, _____ !
Welcome to _____ !

You fill in the blanks with different names and places. That’s exactly what template rendering does!

Why Use Templates?

❌ Without templates (Hard Way):

return "<h1>Hello John!</h1>"
return "<h1>Hello Sara!</h1>"
return "<h1>Hello Mike!</h1>"
# Writing HTML for every person? No way!

βœ… With templates (Easy Way):

# One template, endless possibilities!
return template("hello.html", name=user)

Setting Up Jinja2 Templates

FastAPI uses Jinja2 β€” think of it as your magic paintbrush!

Step 1: Install the magic brush

pip install jinja2

Step 2: Create your templates folder

my_app/
β”œβ”€β”€ main.py
└── templates/
    └── hello.html

Step 3: Connect FastAPI to templates

from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates

app = FastAPI()

# Point to your templates folder
templates = Jinja2Templates(
    directory="templates"
)

Your First Template

templates/hello.html:

<!DOCTYPE html>
<html>
<head>
    <title>Welcome!</title>
</head>
<body>
    <h1>Hello, {{ name }}!</h1>
    <p>Welcome to {{ place }}!</p>
</body>
</html>

See those {{ }} curly braces? That’s where the magic happens! They’re like blank spaces waiting to be filled.

main.py:

@app.get("/greet/{name}")
async def greet(request: Request, name: str):
    return templates.TemplateResponse(
        "hello.html",
        {
            "request": request,
            "name": name,
            "place": "FastAPI Land"
        }
    )

Visit /greet/Emma and see:

Hello, Emma! Welcome to FastAPI Land!


Template Magic Tricks πŸͺ„

graph TD A["🎨 Template File"] --> B{Jinja2 Engine} C["πŸ“Š Your Data"] --> B B --> D["✨ Beautiful HTML Page"]

Trick 1: Loops β€” Show Many Items

Show a shopping list:

<ul>
{% for item in shopping_list %}
    <li>{{ item }}</li>
{% endfor %}
</ul>

Python:

return templates.TemplateResponse(
    "list.html",
    {
        "request": request,
        "shopping_list": ["Apples", "Bread", "Milk"]
    }
)

Trick 2: Conditions β€” Show or Hide

{% if user_logged_in %}
    <p>Welcome back, {{ username }}!</p>
{% else %}
    <p>Please log in.</p>
{% endif %}

Trick 3: Filters β€” Transform Data

<!-- Make text uppercase -->
<h1>{{ title | upper }}</h1>

<!-- Format numbers -->
<p>Price: ${{ price | round(2) }}</p>

<!-- Default values -->
<p>Hello, {{ name | default("Guest") }}!</p>

The Request Object β€” Always Required!

⚠️ Important Rule: Always pass request to your template!

# βœ… Correct
{
    "request": request,  # Always first!
    "name": "John"
}

# ❌ Wrong - missing request
{
    "name": "John"
}

Why? Templates need to know about the visitor’s request to work properly!


πŸ“¦ Part 2: Static Files

Decorating Your Gallery

What are Static Files?

Static files are things that don’t change β€” they look the same for everyone:

  • 🎨 CSS files β€” Make things pretty
  • πŸ–ΌοΈ Images β€” Pictures and icons
  • ⚑ JavaScript β€” Add interactivity
  • πŸ“„ Fonts β€” Custom text styles

They’re called β€œstatic” because unlike templates, they don’t get filled with different data.


Setting Up Static Files

Step 1: Install the helper

pip install aiofiles

Step 2: Create your static folder

my_app/
β”œβ”€β”€ main.py
β”œβ”€β”€ templates/
└── static/
    β”œβ”€β”€ css/
    β”‚   └── style.css
    β”œβ”€β”€ js/
    β”‚   └── app.js
    └── images/
        └── logo.png

Step 3: Tell FastAPI where to find them

from fastapi.staticfiles import StaticFiles

app.mount(
    "/static",           # URL path
    StaticFiles(directory="static"),
    name="static"        # Name for reference
)

Using Static Files in Templates

In your HTML template:

<!DOCTYPE html>
<html>
<head>
    <!-- Link to CSS -->
    <link rel="stylesheet"
          href="{{ url_for('static', path='css/style.css') }}">
</head>
<body>
    <!-- Show an image -->
    <img src="{{ url_for('static', path='images/logo.png') }}"
         alt="Logo">

    <!-- Link to JavaScript -->
    <script src="{{ url_for('static', path='js/app.js') }}">
    </script>
</body>
</html>

The url_for() function creates the correct path automatically!


Complete Example πŸŽ‰

Folder structure:

my_app/
β”œβ”€β”€ main.py
β”œβ”€β”€ templates/
β”‚   └── home.html
└── static/
    └── css/
        └── style.css

static/css/style.css:

body {
    font-family: Arial, sans-serif;
    background-color: #f0f8ff;
    text-align: center;
    padding: 50px;
}

h1 {
    color: #2e7d32;
}

templates/home.html:

<!DOCTYPE html>
<html>
<head>
    <title>{{ title }}</title>
    <link rel="stylesheet"
          href="{{ url_for('static', path='css/style.css') }}">
</head>
<body>
    <h1>{{ message }}</h1>
    <p>Styled with CSS!</p>
</body>
</html>

main.py:

from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles

app = FastAPI()

# Setup templates
templates = Jinja2Templates(directory="templates")

# Setup static files
app.mount("/static",
          StaticFiles(directory="static"),
          name="static")

@app.get("/")
async def home(request: Request):
    return templates.TemplateResponse(
        "home.html",
        {
            "request": request,
            "title": "My App",
            "message": "Welcome to FastAPI!"
        }
    )

🎯 Quick Summary

graph TD A["🌐 User Visits Page"] --> B["FastAPI Route"] B --> C["Template Engine"] C --> D["πŸ“„ HTML Template"] C --> E["πŸ“Š Your Data"] D --> F["✨ Rendered Page"] E --> F F --> G["πŸ“¦ Static Files"] G --> H["🎨 CSS + JS + Images"] H --> I["πŸ‘€ Beautiful Page!"]
Feature Purpose Location
Templates Dynamic HTML pages templates/ folder
Static Files CSS, JS, Images static/ folder
Jinja2 Template engine pip install jinja2
url_for() Link to static files In templates

πŸš€ You Did It!

Now you know how to:

  • βœ… Create HTML templates with Jinja2
  • βœ… Fill templates with dynamic data
  • βœ… Use loops and conditions in templates
  • βœ… Serve CSS, JavaScript, and images
  • βœ… Link static files in your templates

Your web app gallery is ready for visitors! 🎨✨

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.