Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a template exists in Sinatra

In the Sinatra ruby framework, I have a route like this:

get '/portfolio/:item' do
  haml params[:item].to_sym
end

This works great if the template that exists (e.g., if I hit /portfolio/website, and I have a template called /views/website.haml), but if I try a URL that doesn't have a template, like example.com/portfolio/notemplate, I get this error:

Errno::ENOENT at /portfolio/notemplate
No such file or directory - /.../views/notemplate.haml

How can I test and catch whether the template exists? I can't find an "if template exists" method in the Sinatra documentation.

like image 479
Eric Wright Avatar asked Dec 30 '22 13:12

Eric Wright


1 Answers

Not sure if there is a Sinatra specific way to do it, but you could always catch the Errno::ENOENT exception, like so:

get '/portfolio/:item' do
  begin
    haml params[:item].to_sym
  rescue Errno::ENOENT
    haml :default
  end 
end
like image 187
ry. Avatar answered Jan 14 '23 16:01

ry.