使用ERB在Redcarpet中的Markdown中。

6

我想让 Markdown 与 .erb 很好地配合使用。我想使用 high_voltage 来呈现解析 Redcarpet 的 markdown 页面(或带有 markdown 部分的普通 .html.erb 文件),但是我很难让它们一起工作。

目前,我有一个名为 markdown_template_handler.rb 的初始化程序,其中包含以下代码:

class MarkdownTemplateHandler
  def erb
    @erb ||= ActionView::Template.registered_template_handler(:erb)
  end

  def call(template)
    compiled_source = erb.call(template)
    markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML)

    "#{markdown.render(compiled_source.source).inspect}.html_safe;"
  end
end

ActionView::Template.register_template_handler(:md, MarkdownTemplateHandler.new)

然而,它在第7行失败了,compiled_source = erb.call(template),错误代码显示“参数个数不正确(给定1个,需要2个)”

我查看了ERB Ruby文档,但从我理解的内容来看,调用方法是新方法的衍生方法,只需要1个参数,即文本。 但是,当我尝试在快速的rails控制台会话中使用它时,它也需要两个参数。

当我从上面的代码中删除解析erb的要求时,一切都按预期工作,因此我认为这与Redcarpet无关。

我正在使用Rails v6.0.0.rc1和Ruby v2.5.3p105

感谢任何帮助。

编辑

进一步研究使我找到了Rails 6.0 ERB ActionView模板处理程序。 该处理程序的call方法确实需要两个参数,即模板和源代码。 也就是说,在Rails 5.2.3中,ERB Action View模板处理程序的call方法只需要一个参数,即模板。

请问有谁可以指点我找出在此上下文中的源代码是什么? 我找不到任何关于它的文档。


2个回答

7
在这种情况下,当调用处理程序时,ActionView 将通过源传递给 call。您将像这样重写 call 函数:
def call(template, source)
  compiled_source = erb.call(template, source)
  markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML)

  "#{markdown.render(compiled_source).inspect}.html_safe;"
end

在Rails 6之前,“source”值是从“template.source”中提取的,但现在作为单独的参数传递。

6

在Rails 6中,使用ERB呈现Markdown的这种方法对我来说效果很好。 感谢Louis-Michel为我指点迷津,在调用中包括两个参数。

require 'redcarpet'

class MarkdownTemplateHandler

  def erb
    @erb ||= ActionView::Template.registered_template_handler(:erb)
  end

  def call(template, source)
    compiled_source = erb.call(template, source)
    "Redcarpet::Markdown.new(Redcarpet::Render::HTML.new).render(begin;#{compiled_source};end).html_safe"
  end

end

ActionView::Template.register_template_handler(:md, MarkdownTemplateHandler.new)

1
这对我来说在Rails 7上运行得非常好。 - erwin
我遇到了一个错误,错误的参数类型 ActionView::OutputBuffer(期望的是 String)。看起来是来自一个渲染调用。我正在深入研究。 - undefined
1
可能是 Redcarpet#render API 发生了变化。这在 Rails 7.1 中是有效的(添加 .to_s):"Redcarpet::Markdown.new(Redcarpet::Render::HTML.new).render(begin;#{compiled_source};end.to_s).html_safe" - undefined
@Dogweather 这不是因为Redcarpet#render API的变化,而是因为Rails 7.1 ActionView的变化。我在这里详细记录了细节,请参阅:https://stackoverflow.com/a/77549305/9185715 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接