【问题标题】:Using simple_format and html_safe at the same time in Rails在 Rails 中同时使用 simple_format 和 html_safe
【发布时间】:2013-04-23 11:55:22
【问题描述】:

@post.content,我要

1.simple_format,因此内容会有不同的行而不是单行而没有中断

2.html_safe,因此用户可以粘贴一些<embed> 视频链接,例如 youtubes

<%= simple_format @post.content %><%= @post.content.html_safe %>可以分开使用

但是当我将它们一起使用时:<%= simple_format @post.content.html_safe %>,html_safe 不起作用,因此不会显示<embed> 视频

您能告诉我如何同时启用<embed>code 和simple_format?还是有其他解决方案来显示@post.content?谢谢!!!

【问题讨论】:

  • simple_format(@post.content).html_safe 怎么样?这将在 simple_format 的输出上调用 html safe,而不是在 post.content 的 html_safe 版本中“简单格式化”。
  • 嗯....还是不行....
  • 你能显示@post.content的输出吗?
  • 与simple_format @post.content.html_safe 相同,不显示<embed> 代码。 apneadiving 的答案是有效的

标签: ruby-on-rails html-safe


【解决方案1】:

我会告诉simple_format 不要清理我的内容:

simple_format(@post.content, {}, :sanitize => false)

【讨论】:

    【解决方案2】:

    我正在解决类似的问题。

    我正在尝试在我的博客文章中发布代码 sn-ps。它工作得很好,但是 里面的任何东西都会被去掉。无论是我显示还是更复杂的东西, 中的任何东西都会消失。我已经运行了

    问题是我的块中的代码实际上改变了我的页面布局。 :)。

    我最终选择了 Redcarpet 作为我的答案。

    这很简单。

    将 gem 'redcarpet' 添加到您的 Gemfile 并重新启动您的 Rails 服务器。

    在 application_helper.rb 中放入以下代码:

    def markdown(content)
      @markdown ||= Redcarpet::Markdown.new(Redcarpet::Render::HTML, autolink: true, space_after_headers: true, fenced_code_blocks: true)
      @markdown.render(content)
    end    
    

    此处的选项在文档中进行了描述。但是,fenced_code_blocks: true 允许您按照描述将代码放入块中。

    无论您输入什么,它都会在此处输出,并且可以与您的嵌入一起使用。

    然后,在你的情况下呈现它:

    markdown(@post.content).html_safe

    应该不错。您还可以选择缩进四个空格,如此处插入代码。不过,做围栏似乎更容易。

    【讨论】:

    • 这类似于上面 simple_format(@post.content).html_safe 的解决方案,适用于此处的嵌入问题。但是,在我的情况下,我有 Javascript 和 Coffeescript 我想展示并执行 simple_format 选项展示了它,但是我的 pre 块中的代码重新格式化了我的整个页面。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多