Django – get HTML output into a variable
Question:
instead of using render_to_response
which will send the HTML output back to browser.
I would like to take the results, generate HTML (using templates) & output the html into a variable in my views.py
. How can I do this?
Answers:
Adapted from the Django docs:
from django.template import Context, Template
t = Template("My name is {{ my_name }}.")
c = Context({"my_name": "Adrian"})
output = t.render(c)
SOLVED! the way to do this –
from django.template.loader import render_to_string
rendered = render_to_string('my_template.html', { 'foo': 'bar' })
thanks to ned for pointing to the Django docs
There is even a simpler way (if you need to extract html data from render method):
R = render('template.html', context)
data = str(R.content)
instead of using render_to_response
which will send the HTML output back to browser.
I would like to take the results, generate HTML (using templates) & output the html into a variable in my views.py
. How can I do this?
Adapted from the Django docs:
from django.template import Context, Template
t = Template("My name is {{ my_name }}.")
c = Context({"my_name": "Adrian"})
output = t.render(c)
SOLVED! the way to do this –
from django.template.loader import render_to_string
rendered = render_to_string('my_template.html', { 'foo': 'bar' })
thanks to ned for pointing to the Django docs
There is even a simpler way (if you need to extract html data from render method):
R = render('template.html', context)
data = str(R.content)