Reputation: 3318
I would like to have my Sinatra app include a view specific stylesheet in the layout.
Consider this simple app:
app_folder_root/
| my_app/
| my_app.rb
| public/
| css/
| index.css
| layout.css
| views/
| index.haml
| layout.haml
config.ru
config.ru:
require 'rubygems'
require './my_app/my_app'
map '/' do
run MyApp
end
app.rb:
require 'sinatra/base'
class MyApp < Sinatra::Base
get '/' do
haml :index
end
end
I tried setting a variable in my_app.rb
that sets the name of the view and tried to reference it in layout.haml
, but that did not work (I probably wouldn't have went with this as a final solution to the problem since I felt this was a code smell, but was just trying different possibilities).
This is using Haml, but I am hoping that is irrelevant - thinking it should be the same for erb, etc.
In layout.haml
, I would like to reference the view that will be rendered and include a view specific stylesheet by a naming convention. For example, if index.haml
is going to render, I would like to include css/index.css
. What is the best way to go about doing this?
Upvotes: 0
Views: 1039
Reputation: 3318
I solved this by doing the following:
In index.haml
(at the top) I created or appended an array named views
:
- @views = Array.new unless defined? @views
- @views << 'index'
In layout.haml
I reference @views
:
%head
- @views.each do |view|
- haml_tag :link, {:rel => 'stylesheet', :type => 'text/css', :href => "css/#{view}.css"}
I am a little disappointed with having to check @views
in the view to make sure it is defined before appending to it, but for now it is manageable.
EDIT: Solved the problem with having to check if @views
is defined in each view. In config.ru
add the following:
before do
@views = Array.new
end
I can now remove this line from the views:
- @views = Array.new unless defined? @views
Upvotes: 1