如何通过kramdown ruby​​ gem格式化要处理成html的字符串?

时间:2015-05-03 19:17:56

标签: ruby markdown kramdown

当我将字符串传递给kramdown时,我似乎无法使列表函数正常工作:

例如,这是我的文字:

email_body = "Hi, Tim! Hopefully you get this. I just got your email   address. \n\n My email is x@xcom. \n\n For example, you could tell me: * 3 hours from now\n * 2 days from now at 5pm\n * Wednesday afternoon\n"

email_body = Kramdown::Document.new(email_body).to_html

email_body = "<p>Hi, Tim! Hopefully you get this. I just got your email   address. \n\n My email is x@xcom. \n\n For example, you could tell me: * 3 hours from now\n * 2 days from now at 5pm\n * Wednesday afternoon\n</p>"

我无法将其转换为基于Markdown / kramdown的正确HTML(例如插入<ul>和正确的换行符。

1 个答案:

答案 0 :(得分:1)

如果我们将您的正文文本格式化为heredoc可能会更容易:

email_body = <<BODY
Hi, Tim! Hopefully you get this. I just got your email   address.     

 My email is x@xcom.     

 For example, you could tell me: * 3 hours from now    
 * 2 days from now at 5pm    
 * Wednesday afternoon    
BODY

请注意,您的每个后续行都以空格开头? Normal paragraphs should not be indented。同样要开始一个列表,你需要一个空白行,比如开始新的段落。因此,作为一个heredoc你真正想要的是:

email_body = <<BODY
Hi, Tim! Hopefully you get this. I just got your email   address.

My email is x@xcom.

For example, you could tell me:

* 3 hours from now
* 2 days from now at 5pm
* Wednesday afternoon
BODY

或者作为一行:email_body_single_line = "Hi, Tim! Hopefully you get this. I just got your email address.\n\nMy email is x@xcom.\n\nFor example, you could tell me:\n\n* 3 hours from now\n* 2 days from now at 5pm\n* Wednesday afternoon\n"

然后你接近预期的输出:

output = Kramdown::Document.new(email_body).to_html
=> "<p>Hi, Tim! Hopefully you get this. I just got your email   address.</p>\n\n<p>My email is x@xcom.</p>\n\n<p>For example, you could tell me:</p>\n\n<ul>\n  <li>3 hours from now</li>\n  <li>2 days from now at 5pm</li>\n  <li>Wednesday afternoon</li>\n</ul>\n"