简体   繁体   中英

rails ruby iterate through partials in directory

To those helping.. Thanks. Still no solution but getting closer. The errors i think are because my "file" evaluates to "app/views/main/show/_partial.html.erb". and render adds it's own relative path. So I guess i need to list the file names.. maybe a dir.foreach or dir.glob type command.. i'll keep digging. THANKS!

I have a directory full of partials I would like to call in a page. So I wrote a loop but it yields errors.

<% Dir["app/views/main/show/*"].each do |file| %>
  <%= render #{file} %>
<% end %>

When I replace the render line with a simple

file

it lists the file names so i know the loop and Dir location work. The problem I THINK is that render is looking for a string. So I've tried all sorts of things from searching google and here like the #{file}, creating a variable first, raw,...etc.

also I think render may be looking in a different directory relative the Dir. I'll try out some stuff there to.

How should I be handling this? I'm up for switching from Dir to Dir.foreach or any other strategy that makes sense.

Thanks.

EDIT : Here's the solution I've implemented (directory path changed from above):

 <% Dir["app/views/partials/show/*.html.erb"].each do |file| %> <p> <%= render 'partials/show/' + File.basename(file,'.html.erb').slice!(1..-1) %></p> <% end %> 

file is already a string, so there is no need to escape. Also, you have to give the full path. This should work:

<% Dir["app/views/main/show/*"].each do |file| %>
  <%= render :file => Rails.root.join(file).to_s %>
<% end %>

#{} only works inside double quotes. Eg "#{file}" , but in this case that's not necessary. You can just use file .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM