Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serving static HTML in Rails with a layout file

What's the best way to serve static HTML documents in Rails with a layout? Obviously I could just keep the HTML files in the public/ directory, but then I wouldn't be able to apply a layout, or could I? Otherwise I could put the following in config/routes.rb:

match ':page' => 'static#display', :page => /.+\.html/

Does .+\.html work so it ends with .html? Anyway, assuming it did, I guess I'd have a controller:

class StaticController < ApplicationController
  layout 'static_files'
  def display
    render params[:page]
  end
end

Assuming that works properly, will Ruby unnecessarily try and parse the HTML file as an ERB file? Is there a better mechanism Rails has for this?

like image 953
at. Avatar asked Sep 26 '12 18:09

at.


2 Answers

This tutorial has a pretty good explanation of static pages in rails.

First you can generate the static pages via the rails generator:

rails generate controller StaticPages home help --no-test-framework

Then you can edit your config/routes.rb to look like the following:

SampleApp::Application.routes.draw do
  root to: 'static_pages#home'
  match '/help',    to: 'static_pages#help'
  .
  .
  .
end

And finally in your StaticPages controller you create the home and help methods.

class StaticPagesController < ApplicationController
  def home
  end

  def help
  end
end

UPDATE - quote source: Ruby on Rails Guides - Section 2.1

You’ve heard that Rails promotes “convention over configuration”. Default rendering is an excellent example of this. By default, controllers in Rails automatically render views with names that correspond to valid routes. For example, if you have this code in your BooksController class:

class BooksController < ApplicationController 
  #empty controller
end 

And the following in your routes file:

resources :books 

And if you have a view file app/views/books/index.html.erb, then Rails will render it even without the methods. This should work for any mapped routes/equivalent views.

like image 164
knownasilya Avatar answered Nov 06 '22 17:11

knownasilya


You could use the high_voltage gem by Thoughtbot. It's purpose is to include static pages in Rails, and you use any templating language you like. Internally it works similarly to the solutions proposed here.

You can customize the layout file for every single page served by high_voltage as described here in the Readme.

like image 25
Thomas Klemm Avatar answered Nov 06 '22 16:11

Thomas Klemm