如果声明里面有Sinatra模板

我想仅在特定路线/页面上显示消息。 基本上,如果on / route显示消息。

我试过通过Sinatra Docs,但我找不到具体的方法来做到这一点。 是否有一个Ruby方法可以使这个工作?

编辑:这是我想做的一个例子。

get '/' do erb :index end get '/page1' do erb :page1 end get '/page2' do erb :page2 end *******************             

不知道如何使用Ruby / Sinatra定位当前页面并将其结构化为if语句。

有几种方法可以解决这个问题(顺便说一下,即使你已经使用了ERB,我也会使用Haml,因为它对我来说输入的次数较少,而且显然是一种改进)。 他们中的大多数都依赖于请求帮助程序 ,最常见的是request.path_info

视图中的条件。

在任何视图中,不仅仅是布局:

 %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!!!" 

有条件的路线。

 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? 

before块。

 before do @message = "Page1" if request.path_info == "/page1" end # page1.erb %p= @message unless @message.nil? 

甚至更好

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

或者更好

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

如果你想要这样做的话,我还建议你看一下Sinatra Partial ,因为当你有一份为工作准备好帮手时,处理拆分视图要容易得多。

Sinatra没有“控制器#动作”Rail的概念,所以你找不到实例化当前路线的方法。 在任何情况下,您都可以检查request.path.split('/').last以获得当前路由的相对概念

但是,如果您想要只if request.path == "x"显示某些内容,则更好的方法是将该内容放在模板上,除非该内容必须在布局中的其他位置呈现。 在这种情况下,您可以使用Rail的content_for类的东西。 检查sinatra-content-for 。