Concepts 🚀 Project 🧮 Labs
🧮 Labs / FastAPI / Jinja2 templates — render HTML on the server

Jinja2 templates — render HTML on the server

TemplateResponse renders an HTML file with variables. base.html + child.html pattern.

main.py v3.1
API simulator click Simulate
Click "Simulate" to see what this FastAPI app does.
🧠 How it works

Jinja2Templates(directory='templates') — point at your templates folder. TemplateResponse(template_name, context_dict) — renders the template with the variables. 'request': request is REQUIRED since FastAPI 0.85 — without it you get an error. {% extends 'base.html' %} — child template inherits the shell. {% block name %}...{% endblock %} — named holes the child fills. {{ variable }} — insert a value. {{ obj.method() }} — call a method. {% for x in items %}...{% endfor %} — loop. {% if cond %}...{% endif %} — conditional. {{ x | filter }} — apply a filter (upper, lower, length, default). Templates run SERVER-SIDE — the browser gets pure HTML. Faster first paint than React.

✏️ Try these changes
  • Change 'app_name': 'MyAPI' to 'app_name': 'CoolAPI'
    → title and h1 change
  • Add a new variable 'count': 100 to the context and show it in home.html
    → {{ count }} renders
  • Add a filter: {{ users | length }}
    → shows the count
  • Add an if: {% if users %}...{% else %}No users{% endif %}
    → conditional rendering