我有一个小sinatra应用程序,我用它来运行一个基本的网站。该网站的内容是由客户端提供的,大部分是pdf格式的。因为我不想用<
手动替换所有的<
,用&
替换&
,有没有办法配置HAML/Sinatra自动为我做这件事?
基本上,我有一些像这样的块:
%p
large block of text here...
multi-line so I can see it in my IDE...
more lines here...
我想找到一些配置选项,告诉HAML通过所有的内容和替换不安全的字符与他们的HTML实体对应。
我尝试使用HTMLEntities gem,但这个网站有很多多行段落,我似乎无法让它工作。我的意思是我会在我的server.rb
文件中这样做:
def "/some_url"
@encoder = HTMLEntities.new
haml :some_template
end
在我的模板中:
%p
= @encoder.encode("Really long multiline string...
some more lines here...
and more lines...")
,它会吐出一个错误,关于缺少关闭)
。
您可以使用:escaped
过滤器:
%p
:escaped
A block of text here that might
contain & and <.
输出:<p>
A block of text here that might
contain & and <.
</p>
这不是完全自动的,但可以减少所需的编辑。
也许你正在寻找这个:
require 'cgi'
CGI::escapeHTML('unsafe string <script>kill() && destroy()</script>'
#=> "unsafe string <script>kill() && destroy()</script>"
编辑
现在我真的得到你想要的了。只要使用:escape_html => true
,你就可以在='...text here...'
中包装你的文本,因为所有的字符串都被隐式转义了。
require 'sinatra'
get '/' do
haml :index, :escape_html => true
end
__END__
@@layout
!!! 5
%html
%head
%title Example
%body
= yield
@@index
%p
='Here is some <em>unsafe</em> HTML.'
='<script type="text/javascript">'
='killKittens() && destroyHumanity()'
='</script>'
结果:$ curl localhost:4567
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
<p>
Here is some <em>unsafe</em> HTML.
<script type="text/javascript">
killKittens() && destroyHumanity()
</script>
</p>
</body>
</html>