If I have the following Sinatra code:
get '/hi' do
erb :hello
end
This works great if I have a file called views/hello.erb
. However if I have a file called views/hello.html.erb
Sinatra can't find the file and gives me an error. How do I tell Sinatra I want it to look for .html.erb
as a valid .erb extension?
Sinatra uses Tilt to render its templates, and to associate extensions with them. All you have to do is tell Tilt it should use ERB to render that extension:
Tilt.register Tilt::ERBTemplate, 'html.erb'
get '/hi' do
erb :hello
end
Edit to answer follow-up question. There's no #unregister
and also note that Sinatra will prefer hello.erb over hello.html.erb. The way around the preference issue is to either override the erb
method or make your own render method:
Tilt.register Tilt::ERBTemplate, 'html.erb'
def herb(template, options={}, locals={})
render "html.erb", template, options, locals
end
get '/hi' do
herb :hello
end
That will prefer hello.html.erb, but will still fall back on hello.erb if it can't find hello.html.erb. If you really want to prevent .erb files from being found under any circumstances, you could, I guess, subclass ERBTemplate and register that against .html.erb instead, but frankly that just doesn't sound worth it.