Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render a plain HTML file with Sinatra?

Tags:

ruby

sinatra

I have a simple sinatra application. All I want to do is use it as a wrapper to serve a static HTML file at a specific route. My directory structure looks like this:

/directory
    myhtmlfile.html
    app.rb

My app.rb file looks like this:

require 'sinatra'

get '/myspecialroute' do
    html :myhtmlfile      # i know html is not a method, but this is what I would like to do
end

How can I write this so that I can keep my html file a plain html file but serve it at a special route?

Solution:

Thanks to this, I learned a few different ways to do it:

get '/myspecialroute' do
  File.read('myhtmlfile.html')
end

This will open, read, close, then return the file as a string.

Or there is a helper function to make this cleaner:

get '/myspecialroute' do
  send_file 'myhtmlfile.html'
end
like image 215
Andrew Avatar asked Nov 03 '11 15:11

Andrew


3 Answers

Does send_file do what you want?

e.g.

  get '/myspecialroute' do      send_file 'special.html'   end 
like image 193
Steve Avatar answered Sep 19 '22 06:09

Steve


You can do it like this:

get '/myspecialroute' do   redirect '/myspecialroute.html' end 
like image 28
Uri Avatar answered Sep 21 '22 06:09

Uri


This is work for me:

require 'rubygems'
require 'sinatra'

get '/index.html' do
    @page_title = 'Home'
    @page_id = 'index.html'
    erb :'index.html', { :layout => :'layout.html' }
end
like image 42
Андрей Бодосов Avatar answered Sep 21 '22 06:09

Андрей Бодосов