Rails 将 RegEx 与 render 相结合以选择性地呈现模板
Rails combining RegEx with render to selectively render templates
假设我有以下部分:
_o1_some_note.html.erb
_o2_other_note.html.erb
_o3_last_note.html.erb
...
我想渲染 @counter
变量允许的尽可能多的部分,如下所示:
# Controller
def view
@counter = 2
end
# View
<% (1..@counter).each do |c| %>
<%= render "o#{c}" %>
<% end %>
问题是上面的失败是因为 o1
、o1
、o3
不是部分的实际名称。但我想知道是否有办法解决这个问题,只提供 o#
部分,因为部分名称的其余部分更多用于内部组织。这样,代码就更干净了。
所以这基本上就是说,呈现与此描述匹配的模板文件(使用 RegEx 或其他)
您可以将目录中的文件 glob,然后提取其名称进行渲染。例如:
<% Dir["#{Rails.root}/app/views/partial/location/_#{c}*"].each do |file_path| %>
<%= render file_path.split("/").last %>
<% end %>
假设我有以下部分:
_o1_some_note.html.erb
_o2_other_note.html.erb
_o3_last_note.html.erb
...
我想渲染 @counter
变量允许的尽可能多的部分,如下所示:
# Controller
def view
@counter = 2
end
# View
<% (1..@counter).each do |c| %>
<%= render "o#{c}" %>
<% end %>
问题是上面的失败是因为 o1
、o1
、o3
不是部分的实际名称。但我想知道是否有办法解决这个问题,只提供 o#
部分,因为部分名称的其余部分更多用于内部组织。这样,代码就更干净了。
所以这基本上就是说,呈现与此描述匹配的模板文件(使用 RegEx 或其他)
您可以将目录中的文件 glob,然后提取其名称进行渲染。例如:
<% Dir["#{Rails.root}/app/views/partial/location/_#{c}*"].each do |file_path| %>
<%= render file_path.split("/").last %>
<% end %>