我想出了一個辦法做到這一點對每個視圖基地,使用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,所以我可以使其成爲重用的功能。作爲一個基於類的視圖混合可能更容易?