你能从 Rails 部分中获取该部分的名称吗?

问题描述 投票:0回答:3

是否存在包含可从部分内部访问的部分名称的变量?

render partial: 'foo'

_foo.haml

.name
  = partial_name # would output "foo" 
ruby-on-rails partial-views
3个回答
5
投票

__FILE__
会给你文件名

<% __FILE__.split("/").last.sub(/^_/, "") %>

1
投票

在你的部分:

    <%= partial_class(__FILE__) %>

在 application_helper 中:

    def partial_class(partial)
        partial.split(".").first.split("/").last.sub(/^_/, "")
    end

结果:部分为“_customer-existing.html.erb”,输出为“customer-existing”。我经常使用这个作为部分内部包装 div 上的类名,这样我就可以在 jquery 中使用相同的名称来显示/隐藏部分。

示例:

<div class='<%= partial_class(__FILE__) %>'>
  stuff here that will be show/hideable by partial name.
</div>

0
投票

您可以使用 application_helper 中的助手来实现此目的,并使用 ruby 的自省功能 所以你不必显式传递 FILE 就像迈克的回答一样。

def foo                                                                                                                 
  caller_locations(1, 1).first.path                                                                                     
end
© www.soinside.com 2019 - 2024. All rights reserved.