How to print HTML content from a Django template in a view?


Let’s say I have a template called index.html with a bunch of block tags and variables and URLs. I can display it from my view using the render() function like so:

def index(request):
    return render(request, "index.html", {...})

I would like to print the actual content that is being generated here in a normal python function. Something like this:

def get_html():
    html_content = some_function("index.html", {...}) # Takes in the template name and context

Is this possible to do using Django?

Asked By: darkhorse



You can use render_to_string function. Because render internally uses this function to build the HTML content and it simply pass it down to HTTPResponse class to build the appropriate response from the view.

from django.template.loader import render_to_string
rendered = render_to_string('my_template.html', {'foo': 'bar'})
Answered By: Abdul Niyas P M

Yes you can use Django’s template rendering engine outside of a view by using the Template and Context classses from the django.template module .Here’s an example:

from django.template import Template, Context
from django.template.loader import get_template

def get_html():
    # Load the template
    template = get_template('index.html')

    # Create a context dictionary with the variables you want to use in the template
    context = {'foo': 'bar', 'baz': 'qux'}

    # Render the template with the context
    html_content = template.render(context)

    # Print the rendered HTML
Answered By: Zakaria Zhlat