Module Merb::RenderMixin
In: merb-core/lib/merb-core/controller/mixins/render.rb

Methods

Included Modules

Merb::ControllerExceptions

Classes and Modules

Module Merb::RenderMixin::ClassMethods

Public Class methods

Parameters

base<Module>:Module that is including RenderMixin (probably a controller)

@private

[Source]

    # File merb-core/lib/merb-core/controller/mixins/render.rb, line 9
 9:   def self.included(base)
10:     base.extend(ClassMethods)
11:     base.class_eval do
12:       class_inheritable_accessor :_default_render_options
13:     end
14:   end

Public Instance methods

Get the layout that should be used. The content-type will be appended to the layout unless the layout already contains a "." in it.

If no layout was passed in, this method will look for one with the same name as the controller, and finally one in "application.#{content_type}".

Parameters

layout<~to_s>:A layout, relative to the layout root. Defaults to nil.

Returns

String:The method name that corresponds to the found layout.

Raises

TemplateNotFound:If a layout was specified (either via layout in the class or by passing one in to this method), and not found. No error will be raised if no layout was specified, and the default layouts were not found.

:api: private

[Source]

     # File merb-core/lib/merb-core/controller/mixins/render.rb, line 373
373:   def _get_layout(layout = nil)
374:     return false if layout == false
375:     
376:     layout = layout.instance_of?(Symbol) && self.respond_to?(layout, true) ? send(layout) : layout
377:     layout = layout.to_s if layout
378: 
379:     # If a layout was provided, throw an error if it's not found
380:     if layout      
381:       template_method, template_location = 
382:         _template_for(layout, layout.index(".") ? nil : content_type, "layout")
383:         
384:       raise TemplateNotFound, "No layout found at #{template_location}" unless template_method
385:       template_method
386: 
387:     # If a layout was not provided, try the default locations
388:     else
389:       template, location = _template_for(controller_name, content_type, "layout")
390:       template, location = _template_for("application", content_type, "layout") unless template
391:       template
392:     end
393:   end

Take the options hash and handle it as appropriate.

Parameters

opts<Hash>:The options hash that was passed into render.

Options

:status<~to_i>:The status of the response will be set to opts[:status].to_i

Returns

Hash:The options hash that was passed in.

:api: private

[Source]

     # File merb-core/lib/merb-core/controller/mixins/render.rb, line 348
348:   def _handle_options!(opts)
349:     self.status = opts.delete(:status).to_i if opts[:status]
350:     headers["Location"] = opts.delete(:location) if opts[:location]
351:     opts
352:   end

Iterate over the template roots in reverse order, and return the template and template location of the first match.

Parameters

context<Object>:The controller action or template (basename or absolute path).
content_type<~to_s>:The content type (like html or json).
controller<~to_s>:The name of the controller. Defaults to nil.
locals<Array[Symbol]>:A list of locals to assign from the args passed into the compiled template.

Options (opts)

:template<String>:The location of the template to use. Defaults to whatever matches this context, content_type and controller.

Returns

Array[Symbol, String]:A pair consisting of the template method and location.

:api: private

[Source]

     # File merb-core/lib/merb-core/controller/mixins/render.rb, line 414
414:   def _template_for(context, content_type, controller=nil, template=nil, locals=[])
415:     tmp = self.class._templates_for[[context, content_type, controller, template, locals]]
416:     return tmp if tmp
417: 
418:     template_method, template_location = nil, nil
419: 
420:     # absolute path to a template (:template => "/foo/bar")
421:     if template.is_a?(String) && template =~ %r{^/}
422:       template_location = self._absolute_template_location(template, content_type)
423:       return [_template_method_for(template_location, locals), template_location]
424:     end
425: 
426:     self.class._template_roots.reverse_each do |root, template_meth|
427:       # :template => "foo/bar.html" where root / "foo/bar.html.*" exists
428:       if template
429:         template_location = root / self.send(template_meth, template, content_type, nil)
430:       # :layout => "foo" where root / "layouts" / "#{controller}.html.*" exists        
431:       else
432:         template_location = root / self.send(template_meth, context, content_type, controller)
433:       end
434:     
435:       break if template_method = _template_method_for(template_location.to_s, locals)
436:     end
437: 
438:     # template_location is a Pathname
439:     ret = [template_method, template_location.to_s]
440:     unless Merb::Config[:reload_templates]
441:       self.class._templates_for[[context, content_type, controller, template, locals]] = ret
442:     end
443:     ret
444:   end

Return the template method for a location, and check to make sure the current controller actually responds to the method.

Parameters

template_location<String>:The phyical path of the template
locals<Array[Symbol]>:A list of locals to assign from the args passed into the compiled template.

Returns

String:The method, if it exists. Otherwise return nil.

:api: private

[Source]

     # File merb-core/lib/merb-core/controller/mixins/render.rb, line 457
457:   def _template_method_for(template_location, locals)
458:     meth = Merb::Template.template_for(template_location, [], locals)
459:     meth && self.respond_to?(meth) ? meth : nil
460:   end

Called in templates to append content for later use. Works like throw_content.

@param [Object] obj

  Key used in the thrown_content hash.

@param [String] string

  Textual content. Default to nil.

@yield

  Evaluated with result concatenated to string.

@raise [ArgumentError]

  Neither string nor block given

:api: public

[Source]

     # File merb-core/lib/merb-core/controller/mixins/render.rb, line 523
523:   def append_content(obj, string = nil, &block)
524:     unless string || block_given?
525:       raise ArgumentError, "You must pass a block or a string into append_content"
526:     end
527:     @_caught_content[obj] = "" if @_caught_content[obj].nil?
528:     @_caught_content[obj] << string.to_s << (block_given? ? capture(&block) : "")
529:   end

Called in templates to get at content thrown in another template. The results of rendering a template are automatically thrown into :for_layout, so catch_content or catch_content(:for_layout) can be used inside layouts to get the content rendered by the action template.

Parameters

obj<Object>:The key in the thrown_content hash. Defaults to :for_layout.

:api: public

[Source]

     # File merb-core/lib/merb-core/controller/mixins/render.rb, line 471
471:   def catch_content(obj = :for_layout)
472:     @_caught_content[obj] || ''
473:   end

Called when renderers need to be sure that existing thrown content is cleared before throwing new content. This prevents double rendering of content when multiple templates are rendered after each other.

Parameters

obj<Object>:The key in the thrown_content hash. Defaults to :for_layout.

:api: public

[Source]

     # File merb-core/lib/merb-core/controller/mixins/render.rb, line 539
539:   def clear_content(obj = :for_layout)
540:     @_caught_content.delete(obj) unless @_caught_content[obj].nil?
541:   end

Renders an object using to registered transform method based on the negotiated content-type, if a template does not exist. For instance, if the content-type is :json, Merb will first look for current_action.json.*. Failing that, it will run object.to_json.

Parameter

object<Object>:An object that responds_to? the transform method registered for the negotiated mime-type.
thing<String, Symbol>:The thing to attempt to render via render before calling the transform method on the object. Defaults to nil.
opts<Hash>:An options hash that will be used for rendering (passed on to render or serialization methods like to_json or to_xml)

Returns

String:The rendered template or if no template is found, the transformed object.

Raises

NotAcceptable:If there is no transform method for the specified mime-type or the object does not respond to the transform method.

Alternatives

A string in the second parameter will be interpreted as a template:

  display @object, "path/to/foo"
  #=> display @object, nil, :template => "path/to/foo"

A hash in the second parameters will be interpreted as opts:

  display @object, :layout => "zoo"
  #=> display @object, nil, :layout => "zoo"

If you need to pass extra parameters to serialization method, for instance, to exclude some of attributes or serialize associations, just pass options for it. For instance,

display @locations, :except => [:locatable_type, :locatable_id], :include => [:locatable]

serializes object with polymorphic association, not raw locatable_* attributes.

Options

:template a template to use for rendering :layout a layout to use for rendering :status the status code to return (defaults to 200) :location the value of the Location header

all other options options that will be pass to serialization method

                         like #to_json or #to_xml

Notes

The transformed object will not be used in a layout unless a :layout is explicitly passed in the opts.

:api: public

[Source]

     # File merb-core/lib/merb-core/controller/mixins/render.rb, line 209
209:   def display(object, thing = nil, opts = {})
210:     template_opt = thing.is_a?(Hash) ? thing.delete(:template) : opts.delete(:template)
211: 
212:     case thing
213:     # display @object, "path/to/foo" means display @object, nil, :template => "path/to/foo"
214:     when String
215:       template_opt, thing = thing, nil
216:     # display @object, :template => "path/to/foo" means display @object, nil, :template => "path/to/foo"
217:     when Hash
218:       opts, thing = thing, nil
219:     end
220: 
221:     # Try to render without the object
222:     render(thing || action_name.to_sym, opts.merge(:template => template_opt))
223: 
224:   # If the render fails (i.e. a template was not found)
225:   rescue TemplateNotFound => e
226:     # Merge with class level default render options
227:     # @todo can we find a way to refactor this out so we don't have to do it everywhere?
228:     opts = self.class.default_render_options.merge(opts)
229: 
230:     # Figure out what to transform and raise NotAcceptable unless there's a transform method assigned
231:     transform = Merb.mime_transform_method(content_type)
232:     if !transform
233:       raise NotAcceptable, "#{e.message} and there was no transform method registered for #{content_type.inspect}"
234:     elsif !object.respond_to?(transform)
235:       raise NotAcceptable, "#{e.message} and your object does not respond to ##{transform}"
236:     end
237: 
238:     layout_opt = opts.delete(:layout)
239:     _handle_options!(opts)
240:     throw_content(:for_layout, opts.empty? ? object.send(transform) : object.send(transform, opts))
241:     
242:     meth, _ = _template_for(layout_opt, layout_opt.to_s.index(".") ? nil : content_type, "layout") if layout_opt
243:     meth ? send(meth) : catch_content(:for_layout)
244:   end

Render a partial template.

Parameters

template<~to_s>:The path to the template, relative to the current controller or the template root; absolute path will work too. If the template contains a "/", Merb will search for it relative to the template root; otherwise, Merb will search for it relative to the current controller.
opts<Hash>:A hash of options (see below)

Options (opts)

:with<Object, Array>:An object or an array of objects that will be passed into the partial.
:as<~to_sym>:The local name of the :with Object inside of the partial.
:format<Symbol>:The mime format that you want the partial to be in (:js, :html, etc.)
others:A Hash object names and values that will be the local names and values inside the partial.

Examples

  partial :foo, :hello => @object

The "_foo" partial will be called, relative to the current controller, with a local variable of hello inside of it, assigned to @object.

  partial :bar, :with => ['one', 'two', 'three']

The "_bar" partial will be called once for each element of the array specified by :with for a total of three iterations. Each element of the array will be available in the partial via a local variable named bar. Additionally, there will be two extra local variables: collection_index and collection_size. collection_index is the index of the object currently referenced by bar in the collection passed to the partial. collection_size is the total size of the collection.

By default, the object specified by :with will be available through a local variable with the same name as the partial template. However, this can be changed using the :as option.

  partial :bar, :with => "one", :as => :number

In this case, "one" will be available in the partial through the local variable named number.

:api: public

[Source]

     # File merb-core/lib/merb-core/controller/mixins/render.rb, line 291
291:   def partial(template, opts={})
292: 
293:     # partial :foo becomes "#{controller_name}/_foo"
294:     # partial "foo/bar" becomes "foo/_bar"
295:     template = template.to_s
296:     if template =~ %r{^/}
297:       template_path = File.dirname(template) / "_#{File.basename(template)}"
298:     else
299:       kontroller = (m = template.match(/.*(?=\/)/)) ? m[0] : controller_name
300:     end
301:     template = "_#{File.basename(template)}"
302: 
303:     # This handles no :with as well
304:     with = [opts.delete(:with)].flatten
305:     as = (opts.delete(:as) || template.match(%r[(?:.*/)?_([^\./]*)])[1]).to_sym
306: 
307:     # Ensure that as is in the locals hash even if it isn't passed in here
308:     # so that it's included in the preamble. 
309:     locals = opts.merge(:collection_index => -1, :collection_size => with.size, as => opts[as])
310:     template_method, template_location = _template_for(
311:       template, 
312:       opts.delete(:format) || content_type, 
313:       kontroller, 
314:       template_path, 
315:       locals.keys)
316:     
317:     # this handles an edge-case where the name of the partial is _foo.* and your opts
318:     # have :foo as a key.
319:     named_local = opts.key?(as)
320:     
321:     sent_template = with.map do |temp|
322:       locals[as] = temp unless named_local
323: 
324:       if template_method && self.respond_to?(template_method)
325:         locals[:collection_index] += 1
326:         send(template_method, locals)
327:       else
328:         raise TemplateNotFound, "Could not find template at #{template_location}.*"
329:       end
330:     end.join
331:     
332:     sent_template
333:   end

Render the specified item, with the specified options.

Parameters

thing<String, Symbol, nil>:The thing to render. This will default to the current action
opts<Hash>:An options hash (see below)

Options (opts)

:format<Symbol>:A registered mime-type format
:template<String>:The path to the template relative to the template root
:status<~to_i>:The status to send to the client. Typically, this would be an integer (200), or a Merb status code (Accepted)
:layout<~to_s, FalseClass>:A layout to use instead of the default. This should be relative to the layout root. By default, the layout will be either the controller_name or application. If you want to use an alternative content-type than the one that the base template was rendered as, you will need to do :layout => "foo.#{content_type}" (i.e. "foo.json"). If you want to render without layout, use :layout => false. This overrides layout set by layout method.

Returns

String:The rendered template, including layout, if appropriate.

Raises

TemplateNotFound:There is no template for the specified location.

Alternatives

If you pass a Hash as the first parameter, it will be moved to opts and "thing" will be the current action

:api: public

[Source]

     # File merb-core/lib/merb-core/controller/mixins/render.rb, line 104
104:   def render(thing = nil, opts = {})
105:     # render :format => :xml means render nil, :format => :xml
106:     opts, thing = thing, nil if thing.is_a?(Hash)
107: 
108:     # Merge with class level default render options
109:     opts = self.class.default_render_options.merge(opts)
110: 
111:     # If you don't specify a thing to render, assume they want to render the current action
112:     thing ||= action_name.to_sym
113: 
114:     # Content negotiation
115:     self.content_type = opts[:format] if opts[:format]
116: 
117:     # Handle options (:status)
118:     _handle_options!(opts)
119: 
120:     # Do we have a template to try to render?
121:     if thing.is_a?(Symbol) || opts[:template]
122: 
123:       template_method, template_location = 
124:         _template_for(thing, content_type, controller_name, opts[:template])
125: 
126:       # Raise an error if there's no template
127:       unless template_method && self.respond_to?(template_method)
128:         template_files = Merb::Template.template_extensions.map { |ext| "#{template_location}.#{ext}" }
129:         raise TemplateNotFound, "Oops! No template found. Merb was looking for #{template_files.join(', ')} " + 
130:           "for content type '#{content_type}'. You might have mispelled the template or file name. " + 
131:           "Registered template extensions: #{Merb::Template.template_extensions.join(', ')}. " +
132:           "If you use Haml or some other template plugin, make sure you required Merb plugin dependency " + 
133:           "in your init file."
134:       end
135: 
136:       # Call the method in question and throw the content for later consumption by the layout
137:       throw_content(:for_layout, self.send(template_method))
138: 
139:     # Do we have a string to render?
140:     elsif thing.is_a?(String)
141: 
142:       # Throw it for later consumption by the layout
143:       throw_content(:for_layout, thing)
144:     end
145: 
146:     # If we find a layout, use it. Otherwise, just render the content thrown for layout.
147:     (layout = _get_layout(opts[:layout])) ? send(layout) : catch_content(:for_layout)
148:   end

Called in templates to store up content for later use. Takes a string and/or a block. First, the string is evaluated, and then the block is captured using the capture() helper provided by the template languages. The two are concatenated together.

Parameters

obj<Object>:The key in the thrown_content hash.
string<String>:Textual content. Defaults to nil.
&block:A block to be evaluated and concatenated to string.

Raises

ArgumentError:Neither string nor block given.

Example

  throw_content(:foo, "Foo")
  catch_content(:foo) #=> "Foo"

:api: public

[Source]

     # File merb-core/lib/merb-core/controller/mixins/render.rb, line 503
503:   def throw_content(obj, string = nil, &block)
504:     unless string || block_given?
505:       raise ArgumentError, "You must pass a block or a string into throw_content"
506:     end
507:     @_caught_content[obj] = string.to_s << (block_given? ? capture(&block) : "")
508:   end

Called in templates to test for the existence of previously thrown content.

Parameters

obj<Object>:The key in the thrown_content hash. Defaults to :for_layout.

:api: public

[Source]

     # File merb-core/lib/merb-core/controller/mixins/render.rb, line 481
481:   def thrown_content?(obj = :for_layout)
482:     @_caught_content.key?(obj)
483:   end

[Validate]