2017-08-09 131 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,所以我可以使其成为重用的功能。作为一个基于类的视图混合可能更容易?