0

在我的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

4

2 回答 2

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
于 2013-04-17T18:38:22.297 回答
0

在更合适的地方定义一个简单的方法(也许是应用程序助手?),如下所示:

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
于 2013-04-17T18:46:01.877 回答