kittyminky
kittyminky

Reputation: 485

Sinatra method to set layout

I want to write a method in sinatra to set the layout, something like

def admin_layout
   set :layout, 'admin/layout'
end

I know I can do things like set :erb, layout: :'main/layout' or specify the layout for each action like

get 'admin/login' do
  erb :'admin/login', layout: :'admin/layout'
end

but I'm wondering if there is a way to just abstract that into a method so I don't need to set the layout for each route. I am making an app with a main site and then an admin site, but the admin part is very lightweight, just logging in and being able to edit posts so I am not trying to get too crazy but my current file structure is like this:

db/
models/
public/
  views/
    admin/
    main/
app.rb
config.ru

Upvotes: 1

Views: 4140

Answers (2)

7stud
7stud

Reputation: 48599

I know I can do things like: set :erb, layout: :'main/layout'

No you can't do that--or at least erb will ignore it because it's not an erb specific option. If you could do that, wouldn't that do what you are asking for here:

but I'm wondering if there is a way to just abstract that into a method so I don't need to set the layout for each route.

The method already exists--template():

#Templates:

application_layout = <<END_OF_HAML
%html 
  %head
    %title My App
  %body
    =yield
END_OF_HAML

template :layout do  #Creates a template named :layout
  application_layout 
end

template :page1 do
  '%div.greet Hello World!'  #=> <div class="greet">Hello World!</div>
end

template :page2 do
  '%div#first_name John'     #=> <div id="first_name">John</div>
end

#Routes:  -------------------

get '/page1' do
  haml :page1   #If there is a template named :layout, then the :page1 template will be inserted into the :layout template automatically.
end

get '/page2' do
  haml :page2   #If there is a template named :layout, then the :page1 template will be inserted into the :layout template automatically.
end

Then you can override the default layout, like this:

admin_layout = <<END_OF_HAML
%html 
  %head
    %title Admin Only
  %body
    =yield
END_OF_HAML

template :special_layout do  #Creates a template named :special_layout
  admin_layout
end

get '/page3' do
  haml :special_layout, :layout => false do  #Don't use default layout, i.e the :layout template, instead use :special_layout template
    haml :page3
  end
end

See "Named Templates" here: http://www.sinatrarb.com/intro.html#Named%20Templates

Upvotes: 1

dddd1919
dddd1919

Reputation: 888

Define a layout argument:

def admin_layout
  {:layout, 'admin/layout'}
end

Then you can use this method as a param like

get 'admin/login' do
  ## do ......
  erb :'admin/login', admin_layout
end

Or if you want to judge which layout it will use, change the admin_layout function like:

def admin_layout
  if request.path.start_with?('/admin')
    {:layout, 'admin/layout'}
  else
    {:layout, 'layout'}
  end
end

Upvotes: 3

Related Questions