ruby-on-rails - 在 Ruby 中将换行符解释为 markdown(Github Ma

我在我的网站上使用 markdown 进行评论,我希望用户能够通过按 enter 而不是 space space来创建换行符kbd> 输入 (see this meta question for more details on this idea)

如何在 Ruby 中做到这一点?你会认为 Github Flavored Markdown这正是我所需要的,但是(令人惊讶的是)它有很多问题。

Here's their implementation :

# in very clear cases, let newlines become <br /> tags
text.gsub!(/^[\w\<][^\n]*\n+/) do |x|
  x =~ /\n{2}/ ? x : (x.strip!; x << "  \n")
end

此逻辑要求行以 \w 开头最后换行以创建 <br> .这个要求的原因是你不要乱用列表:(但请参阅下面的编辑;我什至不确定这是否有意义)

* we don't want a <br>
* between these two list items

However, the logic breaks in these cases:

[some](http://google.com)
[links](http://google.com)
*this line is in italics*
another line
> the start of a blockquote!
another line

I.e., in all of these cases there should be a <br> at the end of the first line, and yet GFM doesn't add one

Oddly, this works correctly in the javascript version of GFM.

Does anyone have a working implementation of "new lines to <br>s" in Ruby?

Edit: It gets even more confusing!

If you check out Github's official Github Flavored Markdown repository, you'll find yet another newline to <br> regex!:

# in very clear cases, let newlines become <br /> tags
text.gsub!(/(\A|^$\n)(^\w[^\n]*\n)(^\w[^\n]*$)+/m) do |x|
  x.gsub(/^(.+)$/, "\\1  ")
end

我不知道这个正则表达式是什么意思,但它在上述测试用例上并没有做得更好。

另外,要求行以单词字符开头的“不要乱用列表”的理由似乎不是有效的。即,无论您是否添加 2 个尾随空格,标准 Markdown 列表语义都不会改变。这里:

  • 项目 1
  • 第 2 项
  • 第 3 项

在这个问题的源代码中,“项目 1”后面有 2 个尾随空格,但是如果您查看 HTML,则没有多余的 <br>

这让我想到了将换行符转换为 <br> 的最佳正则表达式s 只是:

text.gsub!(/^[^\n]+\n+/) do |x|
  x =~ /\n{2}/ ? x : (x.strip!; x << "  \n")
end

想法?

最佳答案

我不确定这是否会有所帮助,但我只是使用 simple_format() 来自 ActionView::Helpers::TextHelper

ActionView simple_format

my_text = "Here is some basic text...\n...with a line break."

simple_format(my_text)

output => "<p>Here is some basic text...\n<br />...with a line break.</p>"

即使它不符合您的规范,请查看 simple_format() 源代码 .gsub!方法可能会帮助您编写自己的所需 Markdown 版本。

关于ruby-on-rails - 在 Ruby 中将换行符解释为 markdown(Github Markdown 样式)中的 <br>s,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4230476/

相关文章:

c# - C++ 格式化,如 Visual Studio C# 格式化

r - 通过符号在ggplot2中设置特定的填充颜色

formatting - Go 语言中的打印格式列表

c# - 对混合数字和字符串进行排序

c - printf 格式(%d 与 %u)

python - 格式化复数

java - 打印出数组中的元素,元素之间使用逗号

android - 在用户语言环境中显示日期和时间

php - 使用 PHPExcel 以文本格式读取数字

formatting - 不显示文化的本国货币时的正确货币格式