Ric*_*ich 5 ruby-on-rails erb redcarpet high-voltage ruby-on-rails-6
我试图让 Markdown 与 .erb 很好地配合。我想使用 high_voltage 来呈现用 Redcarpet 解析的降价页面(或带有降价部分的普通 .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)
Run Code Online (Sandbox Code Playgroud)
但是它在第 7 行失败,compiled_source = erb.call(template)错误代码说“参数数量错误(给定 1,预期为 2)”
我查看了ERB Ruby 文档,但据我了解,call 方法是新方法的派生,它只需要 1 个参数,即文本。但是,当我尝试仅在快速 rails 控制台会话中使用它时,它还需要两个参数。
当我从上面的代码中删除解析 erb 的要求时,一切都按预期工作,所以我认为这与 Redcarpet 不工作没有任何关系。
我正在使用 Rails v6.0.0.rc1 & Ruby v2.5.3p105
任何帮助表示赞赏。
编辑
进一步的研究使我找到了Rails 6.0 ERB ActionView 模板处理程序。这个处理程序的调用方法确实需要两个参数,模板和源。也就是说,在Rails 5.2.3 中,ERB 操作视图模板处理程序调用方法只需要一个参数,即模板。
有人可以指出我在这种情况下找出什么来源的方向吗?没有我可以找到的文档。
小智 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)
Run Code Online (Sandbox Code Playgroud)
在这种情况下,call当处理程序被调用时,源将被传递给ActionView。
你会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
Run Code Online (Sandbox Code Playgroud)
在 Rails 6 之前,该source值是从 中提取的 template.source,但现在作为单独的参数传递。
| 归档时间: |
|
| 查看次数: |
919 次 |
| 最近记录: |