[英]check a key is available in a hash in ruby
I have a partial named test in rails and I am sending some data in locals hash, I need to check if title exists in locals hash. 我在rails中有一个部分命名的test,我正在locals哈希中发送一些数据,我需要检查title是否存在于locals哈希中。
<%= render partial: "/test", :locals => {
:title => "sample title"
}
%>
I tried with 我尝试过
locals.has_key? 'title',
But it is not working. 但这是行不通的。 Can any one help in this?
有人可以帮忙吗?
I need to check if title exists in locals hash.
我需要检查本地哈希中是否存在标题。
Well, for that you have to do local_assigns.has_key? :some_local
好吧,为此您必须执行
local_assigns.has_key? :some_local
local_assigns.has_key? :some_local
. local_assigns.has_key? :some_local
。
<% if local_assigns.has_key?(:some_local) %>
<%= some code here %>
<% end %>
I didn't get the documentation from Rails guide, but I knew this feature, that's why I mentioned it here. 我没有从Rails指南中获得文档 ,但是我知道此功能,所以才在这里提到它。 But here are some discussions on 15700 and 18970 about
local_assigns
on guides. 但是,以下是有关15700和18970的有关
local_assigns
上的local_assigns的讨论。
Finally with the help of @stefan I found out the documentation of the method local_assigns
. 最后,在@stefan的帮助下,我找到了
local_assigns
方法的local_assigns
。
You need to write title as string
,not as symbol
您需要将标题写为
string
,而不是symbol
<%= render partial: "/test", :locals => {"title" => "sample title" } %>
Now locals.has_key? "title"
现在是
locals.has_key? "title"
locals.has_key? "title"
will return true
locals.has_key? "title"
将返回true
You can write 你可以写
<%= render '/test', title: 'sample title' %>
Within the locale you do this: 在语言环境中,您可以执行以下操作:
if defined?(title)
...
end
It's because 'title'
and :title
are separate keys. 这是因为
'title'
和:title
是单独的键。 You can use :title
or 'title'.to_sym
instead. 您可以改用
:title
或'title'.to_sym
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.