How to do static content in Rails?

后端 未结 8 932
孤城傲影
孤城傲影 2020-11-30 17:47

Looking at different options:

One is to just put the static pages in the public/ folder, but I do want the header from layout/application to be consistent.

I

8条回答
  •  一整个雨季
    2020-11-30 18:22

    Rendering an action doesn't make sense. You'll want to render a template (or a file) with a layout.

    # Path relative to app/views with controller's layout
    render :template => params[:path]
    
    # ... OR
    
    # Absolute path. You need to be explicit about rendering with a layout
    render :file => params[:path], :layout => true
    

    You could serve a variety of different templates from a single action with page caching.

    # app/controllers/static_controller.rb
    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
    

    Lastly, we'll need to define a route.

    # config/routes.rb
    map.connect 'static/:path', :controller => 'static', :action => 'show'
    

    Try accessing these static pages. If the path doesn't include a valid template, we'll render the 404 file and return a 404 status.

    • http://localhost:3000/static/static1
    • http://localhost:3000/static/static3
    • http://localhost:3000/static/static2

    If you take a look in app/public you'll notice a static/ directory with static1.html, static2.html and static3.html. After accessing the page for the first time, any subsequent requests will be entirely static thanks to page caching.

提交回复
热议问题