Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If Statement inside Sinatra template

Tags:

ruby

sinatra

I'd like to to show a message only if on a specific route/page. Essentially, if on /route display a message.

I tried going through the Sinatra Docs, but I can't find a specific way to do it. Is there a Ruby method that will make this work?

EDIT: Here's an example of what I'd like to do.

get '/' do
    erb :index
end

get '/page1' do
    erb :page1
end

get '/page2' do
    erb :page2
end

*******************

<!-- Layout File -->
<html>
<head>
    <title></title>
</head> 
<body>
    <% if this page is 'page1' do something %>
    <% else do something else %>
    <% end %>

    <%= yield %>
</body>
</html>

No idea what how to target the current page using Ruby/Sinatra and structure it into an if statement.

like image 937
Erik D Avatar asked Aug 24 '26 04:08

Erik D


1 Answers

There are several ways to approach this (and BTW, I'm going to use Haml even though you've used ERB because it's less typing for me and plainly an improvement). Most of them rely on the request helper, most often it will be request.path_info.

Conditional within a view.

Within any view, not just a layout:

%p
  - if request.path_info == "/page1"
    = "You are on page1"
  - else
    = "You are not on page1, but on #{request.path_info[1..]}"
%p= request.path_info == "/page1" ? "PAGE1!!!" : "NOT PAGE1!!!"

A conditional with a route.

get "/page1" do
  # you are on page1
  message = "This is page 1"
  # you can use an instance variable if you want, 
  # but reducing scope is a best practice and very easy.
  erb :page1, :locals => { message: message }
end

get "/page2" do
  message = nil # not needed, but this is a silly example
  erb :page2, :locals => { message: message }
end

get %r{/page(\d+)} do |digits|
  # you'd never reach this with a 1 as the digit, but again, this is an example
  message = "Page 1" if digits == "1"
  erb :page_any, :locals => { message: message }
end

# page1.erb
%p= message unless message.nil?

A before block.

before do
  @message = "Page1" if request.path_info == "/page1"
end

# page1.erb
%p= @message unless @message.nil?

or even better

before "/page1" do
  @message = "Hello, this is page 1"
end

or better again

before do
  @message = request.path_info == "/page1" ? "PAGE 1!" : "NOT PAGE 1!!"
end

# page1.erb
%p= @message

I would also suggest you take a look at Sinatra Partial if you're looking to do this, as it's a lot easier to handle splitting up views when you have a helper ready made for the job.

like image 67
ian Avatar answered Aug 26 '26 23:08

ian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!