我想出了一个办法做到这一点对每个视图基地,使用Django的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)
我试图使它尽可能通用,这样我就可以把它添加到任何视图。 我用它来编写一个迭代调用所有模板并将它们全部转换的视图,所以更接近“collectstatic”功能
我不知道如何从渲染参数中获取template_name,所以我可以使其成为重用的功能。作为一个基于类的视图混合可能更容易?