【问题标题】:Render django template as html file将 django 模板渲染为 html 文件
【发布时间】:2018-01-17 13:52:54
【问题描述】:

我需要将一个 django 项目移动到一个 php 服务器上,并且我希望尽可能多地保留前端。 有没有一种简单的方法可以将模板呈现为未标记的 HTML 文件并将它们存放到“template_root”中,就像使用静态文件和媒体文件一样?

或者至少有一个视图在页面加载时渲染并将生成的 html 保存到文件中? (仅供开发人员使用!)

我不关心视图中的动态数据,只是不想重写所有“扩展”和“包含”和“静态文件”或自定义模板标签

【问题讨论】:

    标签: html django-templates


    【解决方案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,所以我可以将它作为一个函数来重复使用。作为基于类的视图混合可能更容易?

    【讨论】:

      猜你喜欢
      • 2012-10-27
      • 2017-02-11
      • 1970-01-01
      • 2012-01-08
      • 1970-01-01
      • 2014-03-15
      • 2022-07-22
      • 2015-09-21
      • 2014-10-05
      相关资源
      最近更新 更多