Updated tests
[sinatra.git] / lib / sinatra / context / renderer.rb
blob3ccfbc15409eae6316c6e06fcd75a7914769ca9a
1 module Sinatra
3   # The magic or rendering happens here.  This is included in Sinatra::EventContext on load.
4   # 
5   # These methods are the foundation for Sinatra::Erb and Sinatra::Haml and allow you to quickly
6   # create custom wrappers for your favorite rendering engines outside of erb and haml.
8   module Renderer
10     Layouts = Hash.new # :nodoc:
11     
12     DEFAULT_OPTIONS = {
13       :views_directory => 'views',
14       :layout => :layout
15     }
16                 
18     # Renders templates from a string or file and handles their layouts:
19     #
20     # Example:
21     #   module MyRenderer
22     #     def my(template, options, &layout)
23     #       render(template, :my, options, &layout)
24     #     end
25     #     
26     #     def render_my(template)
27     #       template.capitalize  # It capitalizes templates!!!!!  WOW!
28     #     end
29     #   end
30     #   Sinatra::EventContext.send :include, MyRenderer
31     # 
32     #   get '/' do
33     #      my "something"
34     #   end
35     # 
36     #   get_it '/' # => 'Something'
37     # 
38     # The second method is named render_extname.  render will call this dynamicly
39     # 
40     # paramaters:
41     # * +template+  If String, renders the string.  If Symbol, reads from file with the basename of the Symbol; uses +renderer+ for extension.
42     # * +renderer+  A symbol defining the render_ method to call and the extension append to +template+ when looking in the +views_directory+
43     # * +options+   An optional Hash of options (see next section)
44     # 
45     # options:
46     # * +:views_directory+ Allows you to override the default 'views' directory an look for the template in another
47     # * +:layout+          Which layout to use (see Sinatra::Dsl).  false to force a render with no layout.  Defaults to :default layout
48     #
49     def render(template, renderer, options = {})
50       options = DEFAULT_OPTIONS.merge(options)
51       
52       layout = block_given? ? yield : Layouts[options[:layout]]
53       
54       result_method = 'render_%s' % renderer
55       
56       if layout
57         send(result_method, layout) { send(result_method, determine_template(template, renderer, options)) }
58       else
59         send(result_method, determine_template(template, renderer, options))
60       end
61     end
62     
63     protected
64     
65       def determine_template(template, ext, options)
66         if template.is_a?(Symbol)
67           File.read("%s/%s.%s" % [options[:views_directory], template, ext])
68         else
69           template
70         end
71       end
72       
73   end
74   
75 end