【问题标题】:How to remove all html tags from django template?如何从 django 模板中删除所有 html 标签?
【发布时间】:2012-10-11 09:43:38
【问题描述】:

我想使用 django 模板发送电子邮件。 但我应该有两个版本的电子邮件 - html 和纯文本。第一个版本生成如下:

template_values = {
     'company_id': company.id
     }
template_file = os.path.join(os.path.dirname(__file__), 'templates/email.html')
html = template.render(template_file, template_values)

现在我应该从同一个文件生成纯文本 - templates/email.html,但它包含我应该删除的 html 标签(如 <div style="font-size:13px; margin: 14px; position:relative">)(链接应该保留,但应该用纯文本替换,例如。 , <a href="http://example.com">Example</a> 应替换为 Example (http://example.com))。

我读到我不应该为此使用正则表达式。什么样的内置 GAE 库可以帮助我?或者有什么办法可以使用django的striptags

【问题讨论】:

  • 实现此目的的常用方法是为其他电子邮件格式“文本”使用另一个模板。
  • @jpic,谢谢。如果我使用单独的纯文本 django 模板,看起来像行尾字符被删除。我该如何避免呢?

标签: python django google-app-engine django-templates


【解决方案1】:

获得 HTML 后,您需要执行以下操作:

from django.utils.html import strip_tags

template_values = {
     'company_id': company.id
}
template_file = os.path.join(os.path.dirname(__file__), 'templates/email.html')
html = template.render(template_file, template_values)

plain_text = strip_tags(html)

【讨论】:

    猜你喜欢
    • 2018-02-11
    • 2011-10-17
    • 2011-09-30
    • 2015-12-13
    • 2011-03-02
    • 2018-09-21
    • 2019-03-04
    • 2013-04-28
    • 2015-10-09
    相关资源
    最近更新 更多