I am porting a plain HTML/CSS/JS site to using Sinatra for its backend. The main thing I’m interested in is templates. For now, I have a views directory with HTML files named like “index.html.erb” and a layout named “layout.html.erb”. While I would like to use Sinatra’s templates with erb, the site I’m working on is static. In other words, my “index.html.erb” does nothave any erb-specific code in it. I only really need the layout in my views directory, for now.
Is there a way that I can move views/index.html.erb to public/index.html but still wrap it in the template views/layout.html?
require 'rubygems'
require 'sinatra'
get '/index.html' do
@page_title = 'Home'
@page_id = 'index.html'
erb :'index.html', { :layout => :'layout.html' }
end
Having read through the Sinatra Readme, there are two main issues that come up in what you are trying to do. First, static files versus template files: Sinatra doesn’t have a template renderer for plain HTML, so you’d have to use ERB. Since ERB can be plain HTML, the issue with this is that Sinatra can only use a certain list of file extensions for ERB (and
.htmlisn’t one of them).The second issue is that, in your example code, you would have to have the layout folder different from the templates folder (which Sinatra sees as being the same, which is
/viewsby default).With this in mind, the closest you could get to what you are asking is the following:
However, this also has a few problems. First, as mentioned, you would have to name your files with the
.html.erbextension (or, just.erbif you cut the.htmlout of the 7th line above). Additionally, anyone could access the raw template file at/index.html.erbon your server. Therefore, the method that you displayed in your original question is the best way to do what you are trying to do in Sinatra without delivering a plain HTML file.