2017-08-03 173 views

回答

0

這裏是一個解決方案:

import re 
from django.utils.html import strip_tags 

def textify(html): 
    # Remove html tags and continuous whitespaces 
    text_only = re.sub('[ \t]+', ' ', strip_tags(html)) 
    # Strip single spaces in the beginning of each line 
    return text_only.replace('\n ', '\n').strip() 

html = render_to_string('email/confirmation.html', { 
    'foo': 'hello', 
    'bar': 'world', 
}) 
text = textify(html) 

的想法是使用strip_tags刪除HTML標籤和同時保留換行剝離所有額外的空格。

這是結果將如何看起來像:

<div style="width:600px; padding:20px;"> 
    <p>Hello,</p> 
    <br> 
    <p>Lorem ipsum</p> 
    <p>Hello world</p> <br> 
    <p> 
     Best regards, <br> 
     John Appleseed 
    </p> 
</div> 

--->

Hello, 

Lorem ipsum 
Hello world 

Best regards, 
John Appleseed 
相關問題