Topic: render_to_string from a helper
I understand that render and render_to_string are methods on ActionController, not ActionView. Howerver, it's perfectly fine to code something like this:
<%= render :partial => 'forum/show_post', :collection => @forum_thread.forum_posts %>
From a view. So that's some erb magic, I guess.
But, let's assume I've got a bit of logic that is associated with the partial render, and let's assume I want to reuse this bit of logic in several places. So I might as well just DRY up the render call, and stick it into a helper. Well one way of doing that would be to call render_to_string from inside the helper -- while building the ultimate output string.
<%= my_render :partial => 'forum/show_post', :collection => @forum_thread.forum_posts %>
and define my_render in the proper helper file. But in that method, I can't make any calls to render() or render_to_string(), because those methods don't live on ActionView, but on ActionController.
So quite obviously, erb does some kind of magic that allows the code to run from the proper controller object. That would make sense, actually, because now that I think about it, you have access to all the variables, objects and functions defined on the controller from your associated view.
Perhaps all I have to do is pass a self reference into the my_render helper:
<%= my_render self, ... %>
Or maybe instead of putting the code into the helper, stick it into the controller? But that is kind of ugly, because it kind of violates the MVC abstraction... right? I mean, we would not stoop so low as to stick output related code into a controller, would we?
Is there a cleaner way to do this? Can someone help me think about it? Perhaps I can make use of yield inside the my_render method?
Last edited by Slurpy (2006-12-20 12:15:43)