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