36

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?

1
  • There's nothing wrong with answering your own question—StackOverflow actually encourages it. If you did, you'd get three times the cred from me (5 points for the question and 10 for the answer, instead of just 5 for the question). Commented Mar 3, 2017 at 23:36

3 Answers 3

47

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

Sign up to request clarification or add additional context in comments.

2 Comments

Awesome! very useful
hello, can we instead of hardcoding the html file name, get it from db?
22

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)

4 Comments

instead of Template("My name is {{ my_name }}.") can I pass on the html i.e. Template("trial.html") ?
Have you checked the docs?
Not upvoting this, because it doesn't answer the question, which was about using a template file (not text), and the answerer left it to the reader to wade through the docs.
hello @NedBatchelder , can we instead of hardcoding the html file name, get it from db?
0

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)

1 Comment

request is mandatory argument for render() . Docs reference : docs.djangoproject.com/en/3.0/topics/http/shortcuts/#render

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.