【问题标题】:Rails/Redcarpet: Markdown-->HTML with link attributes not working in helperRails / Redcarpet:Markdown->带有链接属性的HTML在帮助器中不起作用
【发布时间】:2012-12-28 23:08:42
【问题描述】:

我的 ApplicationHelper 中有一个函数,并且控制器中有一个完全相同的副本用于预渲染。预渲染以我想要的方式创建链接,target="_blank",但现场渲染不会。我的代码如下:

require 'redcarpet'

module ApplicationHelper
  def markdown(text)
    rndr = Redcarpet::Render::HTML.new(:link_attributes => Hash["target" => "_blank"])
    markdown = Redcarpet::Markdown.new(
                rndr,
                :autolink => true,
                :space_after_headers => true
              )
    return markdown.render(text).html_safe
  end
end

在 rails 控制台中运行它也会正常呈现链接,但没有链接属性。我的控制器中的相同代码按预期工作。

【问题讨论】:

  • 我无法解决这个问题,但感谢您通过渲染器选项添加target 属性的策略。因为我预渲染了所有对我有用的东西。

标签: ruby-on-rails ruby-on-rails-3 redcarpet


【解决方案1】:

我使用自定义降价生成器 (redcarpet v 3.1.2) 来实现这一点

lib/my_custom_markdown_class.rb
class MyCustomMarkdownClass < Redcarpet::Render::HTML
  def initialize(extensions = {})
    super extensions.merge(link_attributes: { target: "_blank" })
  end
end

然后像这样使用它

app/helpers/application_helper.rb
def helper_method(text)
  filter_attributes = {
      no_links:    true,
      no_styles:   true,
      no_images:   true,
      filter_html: true
    }

  markdown = Redcarpet::Markdown.new(MyCustomMarkdownClass, filter_attributes)
  markdown.render(text).html_safe
end

或者,您可以将此 helper_method 放入模型中,并将 filter_attributes 设置为类变量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-16
    • 2016-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多