Mr eel
Rails: Rendering Partials Only When You Have ‘Em
I needed a neat way of including a sub-navigation on certain pages in a web application. Since this sub-nav will turn up in the views for multiple actions, it make sense to have it as a partial.
Now I wanted to do this the Rails way. If the partial is in a controller’s view folder it gets rendered, otherwise… well nothing. This is the behavior we see with Rails automatically linking actions and views together based on their names.
But how to do it?! I am Ruby newbie after all. Thank Sweet Jelly for the internet. I stumbled across this interesting post. It’s about auto-discovering CSS files for controllers. It’s really neat! This served as a good basis for my own partial-discovering code. Like so:
def sub_navigation
view_path = "#{RAILS_ROOT}/app/views/#{controller.controller_name}/"
render_partial('sub_nav') if FileTest.exist?("#{view_path}/_sub_nav.rhtml")
end
This goes into the application_helper.rb file so I can access it in any view. First line in the method sets the file path to the view folder for the current controller.
The second line sez; ‘write out the sub-nav if a sub-nav file exists in this folder’.
The only downside here is we can’t share sub-navs between controllers. I’m gonna have to think about it a bit.
Comments