layouts and templates from files

This commit is contained in:
Blake Mizerany 2007-11-28 21:13:51 -08:00
parent 9d0ce7cddd
commit eaa3227fed
5 changed files with 35 additions and 3 deletions

View File

@ -67,7 +67,8 @@ module Sinatra
module RenderingHelpers
def render(content, options={})
@content = _evaluate_render(%Q{"#{content}"})
template = resolve_template(content, options)
@content = _evaluate_render(template)
layout = resolve_layout(options[:layout], options)
@content = _evaluate_render(layout) if layout
@content
@ -78,13 +79,23 @@ module Sinatra
def _evaluate_render(content, options={})
case content
when String
instance_eval(content)
instance_eval(%Q{"#{content}"})
when Proc
instance_eval(&content)
when File
instance_eval(%Q{"#{content.read}"})
end
end
def resolve_template(content, options={})
case content
when String
content
when Symbol
filename = (options[:views_directory] || 'views') + "/#{content}.#{ext}"
File.new(filename)
end
end
def resolve_layout(name, options={})
return if name == false

View File

@ -48,7 +48,7 @@ context "Layouts (in general)" do
get '/foo' do
@title = 'Welcome to the Hello Program'
render 'Blake', :layout => :foo,
render 'Blake', :layout => :foo_layout,
:views_directory => File.dirname(__FILE__) + "/views"
end

18
test/template_test.rb Normal file
View File

@ -0,0 +1,18 @@
require File.dirname(__FILE__) + '/helper'
context "Templates (in general)" do
specify "are read from files if Symbols" do
get '/from_file' do
@name = 'Alena'
render :foo, :views_directory => File.dirname(__FILE__) + "/views"
end
get_it '/from_file'
body.should.equal 'You rock Alena!'
end
end

1
test/views/foo.html Normal file
View File

@ -0,0 +1 @@
You rock #{@name}!

View File

@ -0,0 +1,2 @@
#{@title}
Hi #{@content}