Reputation: 405
I need to move a django project to to a php server, and i want to keep as much of the front-end as possible. Is there an easy way to render the templates into un-tagged HTML files and deposit them into a "template_root" as with static and media files?
Or at least have a view do the render on page load and save the resulting html to a file? (just for dev!)
i'm not concerned about the dynamic data from the views, just don't want to rewrite all the "extends" and "includes" and "staticfiles" or custom template tags
Upvotes: 1
Views: 2009
Reputation: 405
I came up with a way to do this on a per View bases, using Django's render_to_string:
from django.template.loader import render_to_string
from django.views.generic import View
from django.shortcuts import render
from django.conf import settings
def homepage(request):
context = {}
template_name = "main/homepage.html"
if settings.DEBUG == True:
if "/" in template_name and template_name.endswith('.html'):
filename = template_name[(template_name.find("/")+1):len(template_name)-len(".html")] + "_flat.html"
elif template_name.endswith('.html'):
filename = template_name[:len(template_name)-len(".html")] + "_flat.html"
else:
raise ValueError("The template name could not be parsed or is in a subfolder")
#print(filename)
html_string = render_to_string(template_name, context)
#print(html_string)
filepath = "../templates_cdn/" + filename
print(filepath)
f = open(filepath, 'w+')
f.write(html_string)
f.close()
return render(request, template_name, context)
I tried making it as generic as possible, so i can add it to any view. I've used it to write a view that calls all templates iteratively and converts them all too, so is closer to "collectstatic" functionality
I don't know how to get the template_name from the render args, so i can just make it a function to re-use. Might be easier as a class-based-view mixin?
Upvotes: 1