英文:
How to evaluate Ruby code in Haml as a varaible
问题
我正在使用Haml中的Ruby评估。如果我将变量传递给Haml模板,它不起作用。只有当Ruby代码已经在模板内部(而不是作为变量传递)时才有效。我分享我的源代码以更好地解释
require 'sinatra'
require 'haml'
get '/' do
@user_input = params[:foo_user_input]
puts @user_input
haml :foo
end
__END__
@@ foo
%p= "hello"
<br>
%p= 7*7
<br>
%p= #{@user_input}
<br>
%p This is #{7*7} cake!
<br>
%p This is #{@user_input} cake!
<br>
%p= @user_input
<br>
如果我将 7*7
传递给GET请求,你可以看到我得到的是 7*7
,而不是评估为 49
。只有当我已经将 7*7
放在Haml模板内部时,它才会被评估。
hello
49
This is 49 cake!
This is 7*7 cake!
7*7
英文:
I was playing with ruby evaluation in haml. It doesn't work if i pass a variable to the haml template. it only works if the ruby code is already inside the template (not passed as variable), I'm sharing my source code for better explanation
require 'sinatra'
require 'haml'
get '/' do
@user_input = params[:foo_user_input]
puts @user_input
haml :foo
end
__END__
@@ foo
%p= "hello"
<br>
%p= 7*7
<br>
%p= #{@user_input}
<br>
%p This is #{7*7} cake!
<br>
%p This is #{@user_input} cake!
<br>
%p= @user_input
<br>
if i pass 7*7
to the GET request, as you can see i get exactly 7*7
, where it's not evaluated to 49
. it only gets evaluated if i already place 7*7
in the haml template itself.
hello
49
This is 49 cake!
This is 7*7 cake!
7*7
答案1
得分: 4
当您想要评估存储在字符串变量中的Ruby代码时,您可以像这样使用 eval
:
%p This is #{eval(@user_input)} cake!
警告:但是,从不受信任的来源传递字符串给 eval
。攻击者可以通过您的方法传递代码,将我们的密码上传到他们的服务器或删除您的硬盘。
英文:
When you want to evaluate Ruby code that is store in a string variable, then you can use eval
like this:
%p This is #{eval(@user_input)} cake!
Warning: But never pass strings to eval
from an untrusted source. An attacker could pass code to your method that uploads our passwords to their server or that deletes your hard disk.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论