Rails 3 和 html_safe 混淆(允许在聊天中使用图片(微笑),但拒绝其他一切)
我这里有一个模块,可以替换表情符号(如“:-)”)作为图标:
module Smileize
PATH = "/images/smiles"
SMILES = [/\;\-?p/i, /\$\-?\)/, /8\-?\)/, /\>\:\-?\(/, /\:\-?\*/, /\:\-?o/i, /\:\-?c/i, /\;\-?\)/,
/\:\-?s/i, /\:\-?\|/, /\:\-?p/i, /\:\-?D/i, /\:\-?\?/, /\:\-?\(/, /\:\-?\)/]
def to_icon(key)
return "<img class='smiley' src='#{PATH}/smile#{SMILES.index(key) + 1}.png'/>"
end
module_function :to_icon
end
class String
def to_smile
Smileize::SMILES.each do |smile|
if self =~ smile
self.gsub!(smile, Smileize.to_icon(smile))
end
end
self
end
end
所以图片显示我正在使用 html_safe,如下所示:
<%= @message.text.to_smile.html_safe %>
但它不适合我,因为但是会显示图片和其他标签, 也。
我的问题是:如何只显示我的微笑,而忽略其他标签?
I have here is a module that replaces the smilies (like ":-)") as icons:
module Smileize
PATH = "/images/smiles"
SMILES = [/\;\-?p/i, /\$\-?\)/, /8\-?\)/, /\>\:\-?\(/, /\:\-?\*/, /\:\-?o/i, /\:\-?c/i, /\;\-?\)/,
/\:\-?s/i, /\:\-?\|/, /\:\-?p/i, /\:\-?D/i, /\:\-?\?/, /\:\-?\(/, /\:\-?\)/]
def to_icon(key)
return "<img class='smiley' src='#{PATH}/smile#{SMILES.index(key) + 1}.png'/>"
end
module_function :to_icon
end
class String
def to_smile
Smileize::SMILES.each do |smile|
if self =~ smile
self.gsub!(smile, Smileize.to_icon(smile))
end
end
self
end
end
So pictures show that I'm using html_safe, like this:
<%= @message.text.to_smile.html_safe %>
But it does not suit me, because but pictures will be displayed and other tags, too.
My question is: how to display only my smile, ignoring the other tags?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为你需要这样做:
添加一个像这样的助手:
然后在您的 ERB 中:
ERB 使用
ERB::Util::html_escape
对 HTML 进行编码,因此如果您的目标是 ERB,那么自己使用它是有意义的。在字符串上调用html_safe
会返回当它是 HTML 编码的东西时,ERB 不会管你的东西。请注意,没有可用的
html_safe!
字符串和html_safe
返回 ActiveSupport::SafeBuffer 而不是字符串,因此您必须使用助手,而不是猴子将新方法修补到字符串中。 ActiveSupport 确实将html_safe!
方法修补到 String 中,但它所做的只是引发一个异常,提示“不要这样做”:I think you'll need to do it like this:
Add a helper something like this:
And then in your ERB:
ERB uses
ERB::Util::html_escape
to encode HTML so using it yourself makes sense if you're targeting ERB. Callinghtml_safe
on a string returns you something that ERB will leave alone when it is HTML encoding things.Note that there is no usable
html_safe!
on strings andhtml_safe
returns an ActiveSupport::SafeBuffer rather than a String so you'll have to use a helper rather than monkey patching a new method into String. ActiveSupport does patch anhtml_safe!
method into String but all it does is raise an exception saying "don't do that":