我可以直接从routes.rb渲染布局,没有控制器吗?

我想为网站的管理员和公共部门设置一对风格指南。

每个都需要自己的布局,其中包含静态html的混合和对erb partials的调用(因此静态页面不会剪切它)。 我不需要一个控制器来提供这些页面,我不希望什么是有效的开发内容,使其余的代码混乱。 这让我想知道是否有一种直接渲染布局的方法。

免责声明:我很欣赏这不是我应该经常/永远做的事情,我知道有很多争论为什么这是一个坏主意。 我对这是否可能感兴趣。

有没有办法让我直接从routes.rb渲染布局而无需通过控制器?

出于一些奇怪的原因,我想暂时渲染一个空白的JS文件,并且编写一个控制器对于这种黑客来说感觉太过分了。 感谢@genkilabs的回答,我使用了这个3class轮:

 get 'analytics/some_file.js', to: -> (env) do [200, { 'Content-Type' => 'application/javascript' }, ['']] end 

我想做一些非常愚蠢的事情,所以如果你也这样做,试试这个有用的例子。

 match :movedpage, :to => proc { |env| if Rails.env.production? https://stackoverflow.com/questions/24982111/can-i-render-a-layout-directly-from-routes-rb-without-a-controller/@remote_path = 'http://productionhost.com' elsif Rails.env.staging? https://stackoverflow.com/questions/24982111/can-i-render-a-layout-directly-from-routes-rb-without-a-controller/@remote_path = 'http://staginghost.com' else https://stackoverflow.com/questions/24982111/can-i-render-a-layout-directly-from-routes-rb-without-a-controller/@remote_path = 'http://localhost:3000' end [ 200, {"Content-Type" => "text/html"}, [File.read("public/moved_page.html").gsub('https://stackoverflow.com/questions/24982111/can-i-render-a-layout-directly-from-routes-rb-without-a-controller/@remote_path', https://stackoverflow.com/questions/24982111/can-i-render-a-layout-directly-from-routes-rb-without-a-controller/@remote_path)] ] }, :via => :all 

其中moved_pa​​ge.html是一个静态页面,要求人们更新他们的书签,而https://stackoverflow.com/questions/24982111/can-i-render-a-layout-directly-from-routes-rb-without-a-controller/@remote_path只需输入https://stackoverflow.com/questions/24982111/can-i-render-a-layout-directly-from-routes-rb-without-a-controller/@remote_path等链接。 请注意, <%= %>不起作用,因为您没有视图助手。

所以,有足够的绳索让自己陷入困境^ _ ^

Actualy答案是否定的 ,如果没有控制器,你就无法做到。 但看到一些琐碎的解决方法……

这不公平,但应该工作:

假设你有FooController ,你已经实现了任何逻辑。 现在你想渲染anypage.html.erb而不创建任何特殊的控制器。 方法如下:


  1. 配置到静态页面的路由:

    get '/your/static/page', to: 'foo#anypage'

  2. 实现视图app/views/foo/anypage.html.erb


问题是无法更改视图的路径。 路径取决于您在路由中指定的控制器(示例中为foo )。 另请注意,它将使用指定的FooController布局进行渲染。

它应该按惯例工作,你可以在这里阅读它。


UPDATE

我也发现了非常类似的解决方案。 对于这样的页面,使用ApplicationController似乎更合理。 (请注意, 您无需为其创建操作