ページ

2010年12月4日土曜日

SinatraでHamlを別ファイルに書く

前回書いたhello_haml.rbのビュー部分を別ファイルに書く。

本体となるhello.rbと、viewsフォルダに分ける。

viewsフォルダの中には
 layout.haml
 index.haml
 hello.haml

それぞれ以下のように書いてやればいい。

hello.rb
# -*- coding: utf-8 -*-
require 'rubygems'
require 'sinatra'
require 'haml'
helpers do
include Rack::Utils; alias_method :h, :escape_html
end
get '/' do
haml :index
end
post '/hello' do
haml :hello
end
view raw hello.rb hosted with ❤ by GitHub

views/layout.haml
%html
%body
%h1 Hello World
= yield
view raw layout.haml hosted with ❤ by GitHub

views/index.haml
%p あなたの名前は?
%form{:action=>"/hello", :method=>"POST"}
%input{:type=>"text", :name=>"name"}
%input{:type=>"submit", :value=>"送信"}
view raw index.haml hosted with ❤ by GitHub

views/hello.haml
%p== こんにちは、#{h params[:name]}さん!
%a{:href=> "/"} 戻る
view raw hello.haml hosted with ❤ by GitHub


前回のhello_haml.rbを含む全体をまとめたものとをgithubに上げておいた。
https://github.com/zakuni/hellohaml

0 件のコメント:

コメントを投稿