我想仅在特定路线/页面上显示消息。本质上,如果在/route 上显示一条消息。
我尝试浏览 Sinatra 文档,但找不到具体的方法。是否有 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 语句。
最佳答案
有几种方法可以解决这个问题(顺便说一句,我将使用 Haml,即使您使用了 ERB,因为它对我来说输入更少,而且显然是一种改进)。他们中的大多数依赖于 request helper ,通常是 request.path_info
。
在 View 中有条件。
在任何 View 中,而不仅仅是布局:
%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
block 。
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如果您正在寻找这样做,因为当您有一个准备好完成这项工作的助手时,处理 Split View会容易得多。
关于ruby - Sinatra 模板中的 If 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14079193/