在 html 模板中呈现文本时忽略换行符

Line breaks are ignored when render text in html template

我正在开发一个网站,具有特定角色的用户可以在其中登录并向邮寄列表发送电子邮件。我正在使用 Flask Python 并使用 Mailgun 来发送电子邮件。我正在使用 HTML 模板,电子邮件文本作为参数从视图函数传递到发送电子邮件函数。问题是发送的电子邮件文本忽略了换行符。如果电子邮件正文是:

Line 1
Line 2
Line 3

它将交付为:

Line 1 Line 2 Line 3

我的视图函数是:

@main.route('/send-email-to-mailinglist', methods=['POST', 'GET'])
def send_email_to_mailinglist():
    form = MailToMailingList()
    if form.validate_on_submit():
        form.subject = form.subject.data
        form.email_text = form.email_text.data
        send_email('mailing_list@mydomain.com', 
                    form.subject, 'auth/email/to_mailing_list', 
                    description = "now",
                    sender='info', text = form.email_text)
        return redirect(url_for('.index'))
    return render_template ('send_email_to_all.html', form=form)

我的发送邮件功能是:

def send_email(to, subject, template, **kwargs):  
    app = current_app._get_current_object()
    auth = ('api', app.config['MAILGUN_API_KEY'])
    url = 'https://api.mailgun.net/v3/{}/messages'.format(app.config['MAILGUN_DOMAIN']) 
    data = {
        'from': '<{}@{}>'.format(kwargs['sender'],app.config['MAILGUN_DOMAIN']),
        'to': to,
        'subject': subject,    
        'text': render_template(template + '.txt', **kwargs),
        'html': render_template(template + '.html', **kwargs)
    }
    response = requests.post(url, auth=auth, data=data)
    response.raise_for_status()

HTML 模板的相关部分是:

<!doctype html>
<html>
  <head>
    <meta name="viewport" content="width=device-width">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <style>
    </style>
  </head>
  <body>
..
..
    <p> {{ text }} </p>
..
..
  </body>
</html>

您的问题可能是 render_template 期望 HTML,因此将换行符减少为空格,这是在 HTML 中处理换行符和多个空格的常见行为,请参阅 this answer.

有关如何解决此问题,请参阅 this answer. Of course, you could also manually insert <br /> tags or else use an editor that handles whitespace-to-tag conversions for you, such as CKEditor or TinyMCE