如何将 Ruby 代码作为变量在 Haml 中评估

huangapple go评论51阅读模式
英文:

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 &#39;sinatra&#39;
require &#39;haml&#39;

get &#39;/&#39; do
  @user_input = params[:foo_user_input]
  puts @user_input
  haml :foo
end

__END__

@@ foo

%p= &quot;hello&quot;
&lt;br&gt;
%p= 7*7
&lt;br&gt;
%p= #{@user_input}
&lt;br&gt;
%p This is #{7*7} cake!
&lt;br&gt;
%p This is #{@user_input} cake!
&lt;br&gt;
%p= @user_input
&lt;br&gt;

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.

huangapple
  • 本文由 发表于 2023年6月26日 15:24:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76554404.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定