【问题标题】:How to render django html templates as plain text?如何将 django html 模板呈现为纯文本?
【发布时间】:2021-10-28 14:17:35
【问题描述】:

django 中是否有任何机制可以将 html 呈现为纯文本。例如渲染以下内容:

<h1>Title</h1>
<p>Paragraph</p>

作为:

标题

段落

专门用于附加 HTML 电子邮件的替代文本

编辑:我不是在询问 HTML 字符串。我的意思是没有标签的纯文本。只考虑新线之类的东西。类似于 lynx 浏览器。

【问题讨论】:

    标签: django email template-engine


    【解决方案1】:

    邮寄:

    Django 包含django.core.mail.send_mail 方法

        from django.core import mail
        from django.template.loader import render_to_string
        from django.utils.html import strip_tags
    
        subject = 'Subject'
        # mail_template.html is in your template dir and context key you can pass to 
        # your template dynamically
        html_message = render_to_string('mail_template.html', {'context': 'values'})
        plain_message = strip_tags(html_message)
        from_email = 'From <from@example.com>'
        to = 'to@example.com'
    
        mail.send_mail(subject, plain_message, from_email, [to], html_message=html_message)
    

    这将发送一封电子邮件,该电子邮件在两个支持 html 的浏览器中都可见,并将在残缺的电子邮件查看器中显示纯文本。

    将普通 html 作为字符串发送:

    您可以返回 HttpResponse 并传递其中包含有效 HTML 的字符串

    from django.http import HttpResponse
    
    def Index(request):
        text = """
        <h1>Title</h1>
        <p>Paragraph</p>
        """
        # above variable will be rendered as a valid html
        return HttpResponse(text) 
    

    但好的做法是始终返回一个模板并将模板保存在其他目录中,如果您只想呈现一个标签,这并不重要。您可以为此使用render 方法:

    from django.shortcuts import render
    
    def index(request):
        return render(request, 'index.html')
    

    注意:确保在 settings.py 中的 TEMPLATES 变量中指定模板文件夹,以便 django 知道它应该在哪里呈现模板

    【讨论】:

    • "strip_tags" 是我一直在寻找的东西 非常感谢 Shubham。
    【解决方案2】:

    您可以使用 render_to_string 将模板转换为字符串。

    from django.template.loader import render_to_string
    render_to_string('path_to_template',context={'key','value'})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-11
      • 1970-01-01
      • 1970-01-01
      • 2015-07-20
      • 1970-01-01
      • 1970-01-01
      • 2017-01-31
      • 1970-01-01
      相关资源
      最近更新 更多