sinatra + haml + scss で stylesheet

おはようございます。麺処まつば副店長です。
珍しく朝っぱらからの更新です。

さて、先日まで sinatra + haml でゴニョゴニョやってたんですが、
ふとスタイルシートを使いたくなったので調べてみたら
sinatra は scss のテンプレートに対応しているようです。

ということで、今回は sinatra + haml + scss の使い方について簡単にまとめてみます。
本家→http://www.sinatrarb.com/intro-jp.html

手順はこんなカンジ

  • app.rb
  • views/style.scss
  • views/index.haml

では作っていきましょうー。

app.rb

  1 #coding:utf-8
  2 
  3 require 'rubygems'
  4 require 'sinatra'
  5 require 'haml'
  6 
  7 configure :production do
  8 end
  9 
 10 get '/' do
 11   set :haml, :format => :html5
 12   haml :index
 13 end # end [get /]
 14 
 15 get '/style.css' do
 16   content_type 'text/css', :charset => 'utf-8'
 17   sass :style
 18 end

10〜13行目にかけて「/」へのGETの定義。
15〜18行目にかけて、「/styhle.css」の定義をしています。

views/style.scss

  1 body
  2   padding:     20px
  3   background:  #d3d3d3
  4 
  5 img
  6   margin: 10px
  7   border: 5px
  8   solid:  #000000

scssを使うと、すっきりかけますね。

views/index.haml

  1 !!! XML
  2 !!!
  3 
  4 %html{:lang => "ja"}
  5   %head
  6     %meta{ :content=>"text/html", :charset=>"utf-8" }
  7     %title テスト
  8     %link{ :rel => "stylesheet", :href =>"/style.css" }
  9   %body
 10     #main

8行目で css 呼んでます。

勿論 public 配下において読み込んでも良いんですけど
scss 使うと css が綺麗に書けるからいいですね。