How to render content with Context using Template in Django?
Django template is a powerful built-in feature that most people on the modern web tend to overlook. Even I have myself overlooked this feature for more than 3 years into Django development, to finally embrace it with open arms. Let us first try to see how to render Context
using Template
in Django.
from django.template import Context
from django.template import Template
def render_content_with_context(html_data, context_data):
template = Template(html_data)
context = Context(context_data)
return template.render(context)
html_data = '<h1> Hello {{name}}</h1>'
content_data = {'name': 'argo'}
render_content_with_context(html_data, context_data)
'<h1> Hello argo</h1>'
In the above example, we have passed an HTML template content that needs to be populated using context data.
While working with Django, this kind of approach is helpful to send custom emails. Django Template can be used to populate the email template on the fly without any additional library.