渲染一个操作没有意义。你需要使用布局来渲染一个模板(或文件)。
render :template => params[:path]
render :file => params[:path], :layout => true
使用页面缓存,您可以从单个操作中提供多种不同的模板。
class StaticController < ApplicationController
layout 'static'
caches_page :show
def show
valid = %w(static1 static2 static3)
if valid.include?(params[:path])
render :template => File.join('static', params[:path])
else
render :file => File.join(Rails.root, 'public', '404.html'),
:status => 404
end
end
end
最后,我们需要定义一个路由。
map.connect 'static/:path', :controller => 'static', :action => 'show'
尝试访问这些静态页面。如果路径中不包含有效的模板,我们将呈现404文件并返回404状态。
http://localhost:3000/static/static1
http://localhost:3000/static/static3
http://localhost:3000/static/static2
如果您查看 app/public 目录,您会注意到一个 static/ 目录,其中包含 static1.html、static2.html 和 static3.html。在第一次访问页面后,由于页面缓存,任何后续请求都将完全是静态的。
/hello
。 - Roland Studer