Chapter 17: Rendering HTML with Jinja2
Razor views and Jinja2 templates solve the same broad problem: mix static markup with server-provided data.
Jinja2 layout:
<!-- templates/layout.html -->
<!doctype html>
<html lang="en">
<head>
<title>{% block title %}RecipeVault{% endblock %}</title>
</head>
<body>
<main>{% block content %}{% endblock %}</main>
</body>
</html>
Page:
{% extends "layout.html" %}
{% block title %}Recipes{% endblock %}
{% block content %}
<h1>Recipes</h1>
<ul>
{% for recipe in recipes %}
<li><a href="/recipes/{{ recipe.id }}">{{ recipe.title }}</a></li>
{% endfor %}
</ul>
{% endblock %}
Template practices:
- Pass view models, not raw database sessions.
- Use macros or partials for repeated markup.
- Keep filters simple.
- Use explicit URLs instead of stringly route construction when your routing helper supports it.
- Never mark user content as safe unless it is sanitized.