1

I would like to know if there is any library/module that can convert my django templates into a regular html file.

Let's say i have this django template:

index.html

{% extends "base.html" %}
<p> My name is {{ name }}. Welcome to my site </p>

And i want to convert it to something like this:

index.html

< the content of base.html here >
<p> My name is John Doe. Welcome to my site </p>

Is there any simple utility to do that ?

moctarjallo
  • 1,479
  • 1
  • 16
  • 33

2 Answers2

2

Lets say you want to keep your index.html template file and generate a rendered version of it from a context like {'name' : 'John Doe'} into a file called index2.html. You could achieve this by first getting the text output from rendering index.html with a given context and then writing that to another html file.

I am assuming you have your index.html file in 'templates' inside you django project and you've left BASE_DIR setting to the default value.

import os
from django.template import engines
from django.conf import settings

# Get rendered result as string by passing {'name' : 'John Doe'} to index.html
with open(os.path.join(settings.BASE_DIR, 'templates'), 'r') as f:        
    template = engines['django'].from_string(f.read())
    text = template.render({'name':'John Doe'})

# Write the rendered string into a file called 'index2.html'
with open(os.path.join(settings.BASE_DIR, 'templates','index2.html'), 'w+') as f:
    f.write(text)
Ayaz Hossain
  • 191
  • 7
0

You may already have used render to render out your template in your view like:

return render(request, 'folder/some.html')

Similarly you can do:

html = render(request, 'folder/some.html').content

to get the desired HTML.

This HTML is in bytes format.

Ajit
  • 875
  • 1
  • 10
  • 20