1
<%= form_for @post.comments.new do |f| %> 
    Name:<%= f.text_field :name %><br/> 
    Email:<%= f.text_field :email %><br/> 
    Body:<%= f.text_area :content %><br/> 
    <%= submit_tag "Comment" %> 
<% end %> 

我需要刪除/刪除/清理<script>..</script><style>..</style>標籤。Ruby on Rails:我如何從文本輸入中刪除/刪除/清理腳本,樣式標記?

其他選項是如果有任何腳本,樣式標籤,那麼輸入字段將被視爲空。然後評論將不會被保存。

我如何刪除這些標籤和這些標籤內的代碼?我怎樣才能刪除HTML標籤和HTML標籤內的內容?

回答

6

據我所知,在Rails 3中沒有任何東西可以做到這一點。使用sanitize寶石。

gem 'sanitize'添加到您的Gemfile中,並運行bundle install。只有這一點應該做到。

+0

爲什麼要使用消毒寶石?軌3中沒有任何功能/方法可以做到這一點? – shibly

+0

@guru,不是我所知道的。他們無法從文檔中刪除特定的標籤。 – Dogbert

+0

我在哪裏添加這些行? require'rubygems' require'sanitize' – shibly

2

使用SanitizeHelper

string = '<span id="span_is"><br><br><u><i>Hi</i></u></span>' 
strip_tags(string) #This Will give you "Hi" 
+0

我試圖在IRB用strip_tags>但遇到錯誤,1.9.2-P180:010>用strip_tags(字符串) NoMethodError:從(IRB)對象 \t:未定義的方法'用strip_tags'的主要10 \t從/路徑/要/rubies/ruby-1.9.2-p180/bin/irb:16:in'

' – shibly

+1

在'rails console'中,你可以運行'helper.strip_tags(str)' – Dogbert

+0

我得到了,1.9.2-p180:015> helper.strip_tags(string) NameError:未定義的局部變量或方法'helper'for main:Object \t from(irb):15 \t from /path/to/rubies/ruby-1.9.2-p180/bin/irb :16:'

' – shibly

8

我一直在使用消毒爲此確切的目的。它工作得很好。

添加一個常數,你的應用程序:

YourApp::SANITIZE_FILTER = { 
    :remove_contents => ['script'] 
} 

然後你就可以添加一個輔助方法:

def sanitize_content(content) 
    content = Sanitize.clean(content, YourApp::SANITIZE_FILTER) 
end