Performance: Returning HTML templates
This affects the page load speed by determining how quickly the server can send the rendered HTML to the browser and how fast the browser can display the content.
def view(request): data = get_lightweight_data() return render(request, 'template.html', {'data': data})
def view(request): data = get_heavy_data() html = render_to_string('template.html', {'data': data}) return HttpResponse(html)
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Heavy synchronous template rendering | N/A (server-side) | N/A | Delays initial paint | [X] Bad |
| Lightweight context with Django render shortcut | N/A (server-side) | N/A | Faster initial paint | [OK] Good |
render().render() takes the request, template name, and context data, then returns an HttpResponse with the rendered HTML.home.html with an empty context in a Django view?render(request, template_name, context).{{ greeting }}?
def hello_view(request):
context = {'greeting': 'Hello, Django!'}
return render(request, 'hello.html', context){{ greeting }}, which will be replaced by the value from context, 'Hello, Django!'.def index(request):
return render('index.html', request, {'title': 'Home'})render(request, template_name, context). Here, the template name and request are swapped.render().products to display each product. Other options do not properly render HTML with data.Pass the test and this pattern moves unknown