2017-08-09 130 views
1

我需要將django項目移至php服務器,並且我想盡可能多地保留前端。 有沒有一種簡單的方法可以將模板渲染爲未標記的HTML文件並將它們存放到「template_root」中,就像使用靜態和媒體文件一樣?將django模板渲染爲html文件

或者至少有一個視圖做頁面加載渲染和保存生成的HTML文件? (只用於開發!)

我不關心從視圖中的動態數據,只是不想重寫所有的「擴展」和「包括」和「staticfiles」或自定義模板標籤

回答

1

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