0

我的数据库中有一个包含如下字符串的列:

"Warning set for 7 days.\nCritical Notice - Last Time Machine backup was 118 days ago at 2012-11-16 20:40:52\nLast Time Machine Destination was FreeAgent GoFlex Drive\n\nDefined Destinations:\nDestination Name: FreeAgent GoFlex Drive\nBackup Path: Not Specified\nLatest Backup: 2012-11-17"

我在给用户的电子邮件中显示这些数据。通过执行以下操作,我可以轻松地完美地格式化我的 html 电子邮件中的字段:

simple_format(@servicedata.service_exit_details.gsub('\n', '<br>'))

上面的代码"\n""<br>"标签替换了,simple_format 处理其余的。

我的问题在于如何在纯文本模板中正确格式化。最初我以为我可以只调用该列,因为"\n"我认为纯文本会解释并且一切都会好起来的。然而,这只是简单地吐出带有“\n”的字符串,就像上面显示的那样,而不是根据需要创建换行符。

试图找到一种解析字符串的方法,以便确认换行符。我试过了:

    @servicedata.service_exit_details.gsub('\n', '"\r\n"')
    @servicedata.service_exit_details.gsub('\n', '\r\n')
    raw @servicedata.service_exit_details
    markdown(@servicedata.service_exit_details, autolinks: false) # with all the necessary markdown setup
    simple_format(@servicedata.service_exit_details.html_safe)

没有一个奏效。

谁能告诉我我做错了什么或者我如何才能做到这一点?

我想要的是纯文本确认换行符并将字符串格式化如下:

Warning set for 7 days.
Critical Notice - Last Time Machine backup was 118 days ago at 2012-11-16 20:40:52
Last Time Machine Destination was FreeAgent GoFlex Drive

Defined Destinations:
Destination Name: FreeAgent GoFlex Drive
Backup Path: Not Specified\nLatest Backup: 2012-11-17"
4

1 回答 1

1

我懂了。

您需要区分文字反斜杠后跟字母n作为两个字符的序列,以及通常表示为的 LF 字符(又名换行符)\n

You also need to distinguish two different kinds of quoting you're using in Ruby: singles and doubles. Single quotes are literal: the only thing that is interpreted in single quotes specially is the sequence \', to escape a single quote, and the sequence \\, which produces a single backslash. Thus, '\n' is a two-character string of a backslash and a letter n.

Double quotes allow for all kinds of weird things in it: you can use interpolation with #{}, and you can insert special characters by escape sequences: so "\n" is a string containing the LF control character.

Now, in your database you seem to have the former (backslash and n), as hinted by two pieces of evidence: the fact that you're seeing literal backslash and n when you print it, and the fact that gsub finds a '\n'. What you need to do is replace the useless backslash-and-n with the actual line separator characters.

@servicedata.service_exit_details.gsub('\n', "\r\n")
于 2013-03-30T01:11:08.613 回答