Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add request argument to TemplateResponse #2191

Merged
merged 11 commits into from
Jul 13, 2023
2 changes: 1 addition & 1 deletion docs/templates.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ from starlette.staticfiles import StaticFiles
templates = Jinja2Templates(directory='templates')

async def homepage(request):
return templates.TemplateResponse('index.html', {'request': request})
return templates.TemplateResponse(request, 'index.html')
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this the only thing in the documentation that uses TemplateResponse?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes


routes = [
Route('/', endpoint=homepage),
Expand Down
9 changes: 4 additions & 5 deletions starlette/templating.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,17 +142,16 @@ def get_template(self, name: str) -> "jinja2.Template":

def TemplateResponse(
self,
request: Request,
name: str,
context: dict,
context: typing.Optional[dict] = None,
status_code: int = 200,
headers: typing.Optional[typing.Mapping[str, str]] = None,
media_type: typing.Optional[str] = None,
background: typing.Optional[BackgroundTask] = None,
) -> _TemplateResponse:
if "request" not in context:
raise ValueError('context must include a "request" key')

request = typing.cast(Request, context["request"])
context = context or {}
alex-oleshkevich marked this conversation as resolved.
Show resolved Hide resolved
context.setdefault("request", request)
for context_processor in self.context_processors:
context.update(context_processor(request))

Expand Down
16 changes: 5 additions & 11 deletions tests/test_templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ def test_templates(tmpdir, test_client_factory):
file.write("<html>Hello, <a href='{{ url_for('homepage') }}'>world</a></html>")

async def homepage(request):
return templates.TemplateResponse("index.html", {"request": request})
return templates.TemplateResponse(request, "index.html")

app = Starlette(
debug=True,
Expand All @@ -32,18 +32,12 @@ async def homepage(request):
assert set(response.context.keys()) == {"request"}


def test_template_response_requires_request(tmpdir):
templates = Jinja2Templates(str(tmpdir))
with pytest.raises(ValueError):
templates.TemplateResponse("", {})


def test_calls_context_processors(tmp_path, test_client_factory):
path = tmp_path / "index.html"
path.write_text("<html>Hello {{ username }}</html>")

async def homepage(request):
return templates.TemplateResponse("index.html", {"request": request})
return templates.TemplateResponse(request, "index.html")

def hello_world_processor(request):
return {"username": "World"}
Expand Down Expand Up @@ -72,7 +66,7 @@ def test_template_with_middleware(tmpdir, test_client_factory):
file.write("<html>Hello, <a href='{{ url_for('homepage') }}'>world</a></html>")

async def homepage(request):
return templates.TemplateResponse("index.html", {"request": request})
return templates.TemplateResponse(request, "index.html")

class CustomMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
Expand All @@ -99,15 +93,15 @@ def test_templates_with_directories(tmp_path: Path, test_client_factory):
template_a.write_text("<html><a href='{{ url_for('page_a') }}'></a> a</html>")

async def page_a(request):
return templates.TemplateResponse("template_a.html", {"request": request})
return templates.TemplateResponse(request, "template_a.html")

dir_b = tmp_path.resolve() / "b"
dir_b.mkdir()
template_b = dir_b / "template_b.html"
template_b.write_text("<html><a href='{{ url_for('page_b') }}'></a> b</html>")

async def page_b(request):
return templates.TemplateResponse("template_b.html", {"request": request})
return templates.TemplateResponse(request, "template_b.html")

app = Starlette(
debug=True,
Expand Down