【问题标题】:How to convert django template to html template如何将django模板转换为html模板
【发布时间】:2018-10-09 02:30:55
【问题描述】:

我想知道是否有任何库/模块可以将我的 django 模板转换为常规的 html 文件。

假设我有这个 django 模板:

index.html

{% extends "base.html" %}
<p> My name is {{ name }}. Welcome to my site </p>

我想把它转换成这样的:

index.html

< the content of base.html here >
<p> My name is John Doe. Welcome to my site </p>

有没有什么简单的工具可以做到这一点?

【问题讨论】:

    标签: html django django-templates converters


    【解决方案1】:

    假设您想保留您的 index.html 模板文件并从 {'name' : 'John Doe'} 到一个名为 index2.html 的文件中。您可以通过首先使用给定上下文从渲染 index.html 获取文本输出,然后将其写入另一个 html 文件来实现此目的。

    我假设您的 django 项目中的“模板”中有 index.html 文件,并且您已将 BASE_DIR 设置保留为默认值。

    import os
    from django.template import engines
    from django.conf import settings
    
    # Get rendered result as string by passing {'name' : 'John Doe'} to index.html
    with open(os.path.join(settings.BASE_DIR, 'templates'), 'r') as f:        
        template = engines['django'].from_string(f.read())
        text = template.render({'name':'John Doe'})
    
    # Write the rendered string into a file called 'index2.html'
    with open(os.path.join(settings.BASE_DIR, 'templates','index2.html'), 'w+') as f:
        f.write(text)
    

    【讨论】:

      【解决方案2】:

      您可能已经使用render 在您的视图中呈现您的模板,例如:

      return render(request, 'folder/some.html')

      同样你可以这样做:

      html = render(request, 'folder/some.html').content

      获取所需的 HTML。

      此 HTML 位于 bytes format

      【讨论】:

        猜你喜欢
        • 2017-05-07
        • 2021-04-02
        • 1970-01-01
        • 2015-09-21
        • 2015-08-12
        • 2016-10-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多