I’ve come up with two ways of breaking the rendering of my actions out
into a form of templates, and am wondering which (if either) is
considered “standard practice” by the rails community. Right now the
layout is fairly basic, but I’m trying to break things out into “chunks”
rather than repeating a lot of HTML throughout each main layout, and so
am considering having partials for things like the ‘subnav’, ‘sidebar’,
etc areas.
Currently, I am doing the following:
#app/controllers/company_controller.rb
@partials[‘sidebar’,‘subnav’]
#app/views/layouts/standard.html.erb
<%= render :partials => ‘sidebar’ if @partials.include?(‘sidebar’) %>
…
<%= render :partials => ‘subnav’ if @partials.include?(‘subnav’) %>
Would that be the best way, or would something like this be better:
#app/controllers/company_controller.rb
Gets the current action being processed, in a ‘before_filter’
@action = current_action
#app/views/layouts/standard.html.erb
<%= render :partials => “#{@action}_sidebar” if
partial_exists?("#{@action}_sidebar") %>
…
<%= render :partials => “#{@action}_subnav” if
partial_exists?("#{@action}_subnav") %>
As well, I could go for a combination approach:
#app/controllers/company_controller.rb
Gets the current action being processed, in a ‘before_filter’
@action_partials = []
[:sidebar,:subnav].each { |p| @action_partials[p] = current_action }
def index
Override the subnav partial
@action_partials[‘subnav’] = nil
…
end
#app/views/layouts/standard.html.erb
<%= render :partials => “#{@action_partials[:sidebar]}_sidebar” if
(!@action_partials[:sidebar].nil? and
partial_exists?("#{@action_partials[:sidebar]}_sidebar")) %>
…
<%= render :partials => “#{@action_partials[:subnav]}_subnav” if
(!@action_partials[:subnav].nil? and
partial_exists?("#{@action_partials[:subnav]}_subnavr")) %>
The first approach means checking the current action in the partials if
I need to render differing content based on that action, which I think
is the wrong way to do things.
The second means differing partials on a per-action basis, at the cost
of needing to repeat myself if any actions need a partial to render the
same content.
The third means increased flexibility and customization at the cost of
some code complexity.
I’m just curious if anyone has dealt with anything like this, and what
their approach(es) were?