7

我有一个应用程序,管理员可以创建文章,我使用 markitup markdown 编辑器添加标题等。现在在我看来,我想将此 markdown 文本转换为 html。

因此,在我看来,例如,当管理员写他写的文章时,例如,在视图中文本是粗体的。

我希望你能理解并帮助我。

我安装了 redcarpet 并在我的应用程序助手中放入了这个:

module ApplicationHelper


 def markdown(text)
if text
  markdown = Redcarpet::Markdown.new(
    Redcarpet::Render::HTML.new
  )
  markdown.render(text).html_safe
end

结尾

在我的显示视图中:

 <%= markdown(@article.content) %>

我重新启动了服务器,但出现了一个错误:

未初始化的常量 ApplicationHelper::Redcarpet EDIT 2 :

谢谢所有的作品!!!!!!!

4

3 回答 3

15

kramdown gem 在纯 Ruby提供了一个 HTML 到 Markdown 的解决方案。

irb> html = 'How to convert <b>HTML</b> to <i>Markdown</i> on <a href="http://stackoverflow.com">Stack Overflow</a>.'
=> "How to convert <b>HTML</b> to <i>Markdown</i> on <a href=\"http://stackoverflow.com\">Stack Overflow</a>."
irb> document = Kramdown::Document.new(html, :html_to_native => true)
=> <KD:Document: ... >
irb> document.to_kramdown
=> "How to convert **HTML** to *Markdown* on [Stack Overflow][1].\n\n\n\n[1]: http://stackoverflow.com\n"
于 2015-01-16T10:42:35.777 回答
13

It seems you need this gem

Transform existing html into markdown in a simple way, for example if you want to import existings tags into your markdown based application.

Simple html to Markdown ruby gem We love markdown, cause it is friendly to edit. So we want everything to be markdown

A HTML to Markdown converter.

Upmark defines a parsing expression grammar (PEG) using the very awesome Parslet gem. This PEG is then used to convert HTML into Markdown in 4 steps:

  1. Parse the XHTML into an abstract syntax tree (AST).
  2. Normalize the AST into a nested hash of HTML elements.
  3. Mark the block and span-level subtrees which should be ignored (table, div, span, etc).
  4. Convert the AST leaves into Markdown.

uninitialized constant ApplicationHelper::Redcarpet

Add require 'redcarpet' before module ApplicationHelper

require 'redcarpet'
module ApplicationHelper


  def markdown(text)
    Redcarpet.new(text).html_safe
  end
end
于 2013-06-05T15:24:38.067 回答
4

您可以使用redcarpet gem 将 markdown 编译为 rails 中的 html。


使用 redcarpet,您可以执行以下操作:

# application_helper.rb
module ApplicationHelper

  def markdown(text)
    if text
      markdown = Redcarpet::Markdown.new(
        Redcarpet::Render::HTML.new
      )
      markdown.render(text).html_safe
    end
  end
end

# some_view.html.erb
<%= markdown(@article.body) %>
于 2013-06-05T15:19:51.370 回答