3

我只想在特定路线/页面上显示一条消息。本质上,如果在 /route 上显示一条消息。

我尝试浏览 Sinatra Docs,但找不到具体的方法。有没有一种 Ruby 方法可以使这项工作?

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

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>

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

4

2 回答 2

3

有几种方法可以解决这个问题(顺便说一句,即使你使用了 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

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.

于 2012-12-29T19:20:06.510 回答
1

Sinatra 没有类似 Rail 的“controller#action”概念,因此您不会找到实例化当前路线的方法。在任何情况下,您都可以检查request.path.split('/').last以了解当前路线是什么。

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

于 2012-12-29T17:49:55.643 回答