If Statement inside Sinatra template

℡╲_俬逩灬. 提交于 2019-12-06 01:25:03

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.

Sinatra has no "controller#action" Rail's like concept, so you wont find a way to instantiate the current route. In any case, you can check request.path.split('/').last to get a relative idea of what is the current route.

However, if you want something so be shown only if request.path == "x", a much better way is to put that content on the template, unless that content has to be rendered in a different place within your layout. In that case you can use something like Rail's content_for. Check sinatra-content-for.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!