Reputation: 3966
When returning an HttpResponse
object with render_to_response
you can provide a template and it will use that template and fill in all the {{ variables }}
you've set within your template.
If I want to build my HttpResponse
object manually, is it possible to still use one of my templates in my template directory?
Upvotes: 5
Views: 5994
Reputation: 369064
Using render_to_string
, you will get rendered string. You can pass the returned string to the HttpResponse
.
from django.template.loader import render_to_string
...
rendered = render_to_string('my_template.html', {'foo': 'bar'})
response = HttpResponse(rendered)
Upvotes: 14
Reputation: 6767
Yes - you can use Django's template loader to load your template as a Template
object, and then render it to a string, which you pass to HttpResponse
:
from django.template import Template, Context
from django.template.loader import get_template
def my_view(request):
temp = get_template('/path/to/template.html')
result = temp.render(Context({'context': 'here'})
return HttpResponse(result)
EDIT
Just noticed @falsetru's answer above - that's probably a better and shorter way!
Upvotes: 1