如何在rails中对html_encode变量进行编码?

时间:2010-03-30 01:57:25

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

使用Rails,如果我有一个包含HTML内容的变量,如何输出它,在我的视图文件中未编码?

此代码,例如:

<% my_variable = "<b>Some Bolded Text</b>" %>
<%= my_variable %>

输出:

&lt;b&gt;Some Bolded Text&lt;/b&gt;

2 个答案:

答案 0 :(得分:8)

您使用的是Rails 3 Beta吗? Rails 2默认情况下没有HTML转义输出,你通常必须使用h帮助器,请参阅Nate的帖子。如果您使用的是Rails 3,则需要使用raw帮助程序或将字符串设置为html safe。实例

<% my_variable = "<b>Some Bolded Text</b>" %>
<%= raw my_variable %>

或者

<% my_variable = "<b>Some Bolded Text</b>".html_safe %>
<%= my_variable %>   

检查您的Rails版本并返回给我们。

答案 1 :(得分:0)

ActionView::Helpers::TextHelper提供了一个方法strip_tags,它不是仅仅转义标记,而是完全删除它们。

来源[参考]:

 def strip_tags(html)     
    return html if html.blank?
    if html.index("<")
      text = ""
      tokenizer = HTML::Tokenizer.new(html)
      while token = tokenizer.next
        node = HTML::Node.parse(nil, 0, 0, token, false)
        # result is only the content of any Text nodes
        text << node.to_s if node.class == HTML::Text  
      end
      # strip any comments, and if they have a newline at the end (ie. line with
      # only a comment) strip that too
      text.gsub(/<!--(.*?)-->[\n]?/m, "") 
    else
      html # already plain text
    end 
  end

<%= strip_tags(my_variable) %>