在Sinatra嵌套布局

Pat*_*ell 9 ruby erb sinatra

tl;博士:在Sinatra有一种干净的布局方式吗?

对于我网站上的所有页面,我有一个共同的layout.erb,它呈现一个页眉,一个页脚和一些其他位.

对于这些页面的子集,我想使用内部布局,除了这些公共位之外还会显示左侧菜单.

全球

erb :pageTemplate执行layout.erb,yield执行pageTemplate

在子集中

erb :pageTemplate执行layout.erb,yield执行specificLayout.erb,yield执行pageTemplate.


合理?

我愿意分开课程,在陈述之前,以及任何其他红宝石魔法.我不是在寻找添加页眉/页脚部分并将它们包含在每个布局中.

Pat*_*ell 10

找到了! http://www.sinatrarb.com/intro.html#Templates%20with%20%3Ccode%3Eyield%3C/code%3E%20and%20nested%20layouts

erb :site_layout, :layout => false do
  erb :region_layout do
    erb :page
  end
end
Run Code Online (Sandbox Code Playgroud)

现在,:site_layout可以包含页眉和页脚,:region_layout可以包含左侧导航,:page只需要担心页面内容!


iai*_*ain 4

全球

erb :pageTemplate
Run Code Online (Sandbox Code Playgroud)

在子集中

erb :pageTemplate, :layout => :specificLayout
Run Code Online (Sandbox Code Playgroud)

编辑:

一种方法是使用部分,通过 Erb 或Sinatra Partial(我是维护者,我没有从这个广告中得到任何钱;)

将标志传递给影响渲染的布局:

<html>
<head>
  <title>Example</html>
</head>
<body>
  <%= erb @specificLayout if @specificLayout %>
  <%= yield %>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

在路线中:

@specificLayout = :left_menu
Run Code Online (Sandbox Code Playgroud)

如果您发现一大堆路由需要相同的标志,那么一些继承将会有所帮助:

# one big config.ru
require 'sinatra/base'

class MainController < Sinatra::Base
  configure do
    # lots of shared settings here
    enable :inline_templates
    set :specificLayout, nil
  end

  helpers do
    # all subclasses get these too
    def route
      request.path
    end
  end

  get "/" do
    erb :home
  end
end

class SubWithLeftMenu < MainController
  configure do
    set :specificLayout, :left_menu
  end

  get "/" do
    erb :something
  end
end

map( "/something" ) { run SubWithLeftMenu }
map( "/" ) { run MainController }

__END__

@@ layout

<html>
<head>
  <title>Example</title>
</head>
<body>
  <p>Route: <%= route %></p>
  <%= erb settings.specificLayout if settings.specificLayout %>
  <%= yield %>
</body>
</html>

@@ something

<p>Hello!</p>

@@ home

<p>At home</p>

@@ left_menu

<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
Run Code Online (Sandbox Code Playgroud)

运行它:

$ bin/rackup config.ru &
[1] 40556
[2013-06-21 22:16:34] INFO  WEBrick 1.3.1olumes/RubyProjects/Test/nestinglayouts
[2013-06-21 22:16:34] INFO  ruby 1.9.3 (2013-02-06) [x86_64-darwin10.8.0]
[2013-06-21 22:16:34] INFO  WEBrick::HTTPServer#start: pid=40556 port=9292

$ curl http://localhost:9292/

127.0.0.1 - - [21/Jun/2013 22:16:47] "GET / HTTP/1.1" 200 99 0.0399

<html>
<head>
  <title>Example</title>
</head>
<body>
  <p>Route: /</p>


<p>At home</p>


</body>
</html>


$ curl http://localhost:9292/something/
127.0.0.1 - - [21/Jun/2013 22:16:51] "GET /something/ HTTP/1.1" 200 141 0.0064

<html>
<head>
  <title>Example</title>
</head>
<body>
  <p>Route: /something/</p>

<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>

<p>Hello!</p>


</body>
</html>
Run Code Online (Sandbox Code Playgroud)