在我的Rails
应用中,我已经拥有以下代码:
<% %w(number_of_students edit_class_name tech_help).each do |modal| %>
<%= render "common/modals/#{modal}" %>
<% end %>
app/views/common/modals
中会添加更多模态,而不是在%w()
中明确列出它们,我想要遍历common/modals
目录并只渲染每个文件。
答案 0 :(得分:1)
以下是我提出的建议:
def render_modals
files = Dir.glob("#{Rails.root}/app/views/common/modals/*").collect { |file| File.basename(file, ".html.erb").sub("_", "") }.flatten
files.collect do |modal|
render partial: "common/modals/#{modal}"
end.join.html_safe
end
答案 1 :(得分:0)
定义一个更合适的简单方法(也许是app helper?),如下所示:
def modals
%w(number_of_students edit_class_name tech_help)
end
如果你在控制器/模型中也需要这些模态,也许你应该在适当的类中定义这个方法?例如
class Modal
def self.types
%w(number_of_students edit_class_name tech_help)
end
end
另外,如果您经常渲染模板,那么还要定义
def render_modals
modals.map do |modal| # Modals here should be the method that you just defined, example, Modal.types
render partial: "common/modals/#{modal}"
end.join
end