From eaa3227fedfa8ccc4312b72426c905aa9ae9f9eb Mon Sep 17 00:00:00 2001 From: Blake Mizerany Date: Wed, 28 Nov 2007 21:13:51 -0800 Subject: [PATCH] layouts and templates from files --- lib/sinatra.rb | 15 +++++++++++++-- test/layouts_test.rb | 2 +- test/template_test.rb | 18 ++++++++++++++++++ test/views/foo.html | 1 + test/views/foo_layout.html | 2 ++ 5 files changed, 35 insertions(+), 3 deletions(-) create mode 100644 test/template_test.rb create mode 100644 test/views/foo.html create mode 100644 test/views/foo_layout.html diff --git a/lib/sinatra.rb b/lib/sinatra.rb index 88d254a7..c94184b5 100644 --- a/lib/sinatra.rb +++ b/lib/sinatra.rb @@ -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 diff --git a/test/layouts_test.rb b/test/layouts_test.rb index 68ce362b..890efc52 100644 --- a/test/layouts_test.rb +++ b/test/layouts_test.rb @@ -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 diff --git a/test/template_test.rb b/test/template_test.rb new file mode 100644 index 00000000..a8486132 --- /dev/null +++ b/test/template_test.rb @@ -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 diff --git a/test/views/foo.html b/test/views/foo.html new file mode 100644 index 00000000..8a4ddee5 --- /dev/null +++ b/test/views/foo.html @@ -0,0 +1 @@ +You rock #{@name}! \ No newline at end of file diff --git a/test/views/foo_layout.html b/test/views/foo_layout.html new file mode 100644 index 00000000..ad566518 --- /dev/null +++ b/test/views/foo_layout.html @@ -0,0 +1,2 @@ +#{@title} +Hi #{@content}