I am trying to create a bunch of dynamic helper methods like these:
show_admin_sidebar
show_posts_sidebar
show_users_sidebar
So far I have this in my helper.rb file:
#spits out a partial
def show_sidebar(name, show_sidebar = true)
@content_for_sidebar = render :partial => "partials/#{name}"
@show_sidebar = show_sidebar
end
def show_sidebar?
@show_sidebar
end
In my application layout file I have this: (NB – I’m using HAML):
- if show_sidebar?
= yield(:sidebar)
This allows me to say the following in my views:
- show_sidebar(:foo)
- show_sidebar(:bar)
And this renders the desired partial.
The problem with this is that I can only add one sidebar per page. So, I figure I need to have dynamic methods like: show_admin_sidebar, show_foo_sidebar.
So I have tried to do this:
def show_#{name}_sidebar(show_sidebar = true)
@name = name
@content_for_#{@name}_sidebar = render :partial => "partials/#{@name}"
@show_sidebar = show_sidebar
end
and then in my layout:
- if show_sidebar?
= yield("{@name}_sidebar")
But rails does not like this at all.
I have tried almost everything I can think of in my helper file and nothing works.
The reason I am using helper methods for this is because I want my content div to be 100% page width unless there is a sidebar present in which case the main content goes into a smaller div and the sidebar content goes into it’s own..
If I can’t get this working, then I can easily fix the problem by just adding the partials manually but I’d like to get my head round this….
Anyone got any experience with this kind of thing?
Here is a solution for you, however I wouldn’t suggest too much metaprogramming: