how to route your sub-folder in views Ruby on Rails?

有些话、适合烂在心里 提交于 2019-12-05 05:46:17

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.

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.

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!