Using ERB in Markdown with Redcarpet

岁酱吖の 提交于 2019-12-06 05:13:43

问题


I'm trying to get Markdown to play nicely with .erb. I'd like to use high_voltage to render markdown pages (or normal .html.erb files with markdown partials) that are parsed with Redcarpet and am struggling to get it to all work together.

At the moment I have an initializer called markdown_template_handler.rb that contains the following code:

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)

However it is failing at line 7, compiled_source = erb.call(template) with the error code saying "wrong number of arguments (given 1, expected 2)"

I looked at the ERB Ruby documentation but from what I understood, the call method is a derivative of the new method, which only requires 1 argument, the text. However, when I tried to use it just in a quick rails console session, it also required two arguments.

When I remove the requirement to parse erb from the above code, everything works as expected, so I don't think it has anything to do with Redcarpet not working.

I am using Rails v6.0.0.rc1 & Ruby v2.5.3p105

Any help is appreciated.

Edit

Further research has led me to finding the Rails 6.0 ERB ActionView template handler. The call method of this handler does indeed require two arguments, the template and the source. That said, in Rails 5.2.3, the ERB Action View template handler call method only requires one argument, the template.

Could someone please point me in the direction of figuring out what source is in this context? There is no documentation for it that I can find.



回答1:


In this case, source would be passed to the call by ActionView when the handler is called.

You would rewrite your call function like that:

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

Before Rails 6, the source value was extracted from template.source, but it is now passed as a separate parameter.



来源:https://stackoverflow.com/questions/56715152/using-erb-in-markdown-with-redcarpet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!