how to route your sub-folder in views Ruby on Rail

2019-04-26 23:00发布

问题:

Can anyone please shed some light on how to route your sub-folder's .html.erb files?? which is placed like this:

view/pages/en/index.html.erb

and to route this i am doing following things on route.rb

match ':lang/index', :to => 'pages/en#index'

and for a link code, I have this on the header

<%= link_to "Home", index_path %>

The error i am getting is

 Routing Error
 uninitialized constant Pages

routes:

回答1:

AFAIK, There is no way to route to a view. You can route an URL to a controller's action. That action is responsible for rendering the views.

you can use namespaced routing to put the resources in the sub folder.

...

What i wanted to write already written by @TuteC. Just follow that link and yes you can get language specific thing out of box as he explained.



回答2:

Namespaces will organize your code and views in subfolders: http://guides.rubyonrails.org/routing.html#controller-namespaces-and-routing

If just need only the views/pages folder organized that way, you could do in PagesController something like:

render "#{I18n.locale}/#{action_name}"

A question: why would you like view/pages/en/index.html.erb instead of view/pages/index.en.html.erb? That would work out of the box.



回答3:

UPDATE This is how it works for route.rb:-

match ':lang/index', :to => 'pages#index'

Render it on your controller:-

def index
  render "pages/en/index"
end

def about
  render "pages/#{params[:lang]}/about"
end


回答4:

I have been struggling with this for a while and finally figured out an easy solution:

config/routes.rb

get 'pages/:first/:second/:third' => 'pages#show'

Then in your PagesController

def show
    render "/pages/#{params[:first]}/#{params[:second]/#{params[:third]}"
end

Then in your views it will render any of the following:

pages/index => pages/index.html.erb
pages/index/en => pages/index/en.html.erb
pages/foo/bar/hello-world => pages/foo/bar/hello_world.html.erb

The best thing about this is that it is simple and you can extend it indefinitely. Allows easy cleaning up of the views folders if all you are doing is rendering basic templates.