2012-10-21 91 views
3

我想使用django模板进行电子邮件发送。 但我应该有两个版本的电子邮件 - HTML和纯文本。第一个版本是一样产生如下:如何从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

+2

一种常见的方式实现这一目标是使用另一个模板为其他电子邮件格式“文本”。 – jpic

+1

[django-templated-email](https://github.com/bradwhittington/django-templated-email) –

+0

@jpic,谢谢。如果我使用单独的纯文本Django模板,看起来像行尾字符被删除。我怎样才能避免它? –

回答

7

一旦你的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)