Calling render_to_string from a view

I’m playing around with a list of todos, which I want to render as

    's that can nest to an arbitrary level, so I wrote this as a helper method:
def print_todo(t)
    str = "<ul>\n\t<li>"

    str += render_to_string(:partial => 'todo', :object => t) + "\n"
    t.children.each { |c| str += print_todo(c) }

    str += "\n\t</li>\n</ul>"
    return str
end

Unfortunately, I can’t call this from the view because of the
render_to_string call. What’s the correct way to write this kind of
functionality? I need the list elements to set up indentation, but I’ve
also got a clean little partial for the actual contents.

Thanks!
Austin

Austin McKinley wrote:

I’m playing around with a list of todos, which I want to render as

    's that can nest to an arbitrary level, so I wrote this as a helper method:
def print_todo(t)
    str = "<ul>\n\t<li>"

    str += render_to_string(:partial => 'todo', :object => t) + "\n"
    t.children.each { |c| str += print_todo(c) }

    str += "\n\t</li>\n</ul>"
    return str
end

Unfortunately, I can’t call this from the view because of the
render_to_string call. What’s the correct way to write this kind of
functionality? I need the list elements to set up indentation, but I’ve
also got a clean little partial for the actual contents.

Thanks!
Austin

Interesting. Would it not be possible to just nest the partials: this
would be _todo_list.rhtml:

  • <%= render :partial=>"todo", :object=>t <% t.children.each do |child| -%> <%= render: partial=>"todo_list", :object=>child %> <% end -%>

I just tested this recursion in a simple way - it definitely works in
principle :slight_smile:

Cheers,

Robert J.

Robert J. wrote:

Interesting. Would it not be possible to just nest the partials: this
would be _todo_list.rhtml:

  • <%= render :partial=>"todo", :object=>t <% t.children.each do |child| -%> <%= render: partial=>"todo_list", :object=>child %> <% end -%>

I just tested this recursion in a simple way - it definitely works in
principle :slight_smile:

Cheers,

Robert J.

Yep, that works perfectly! Nice solution :slight_smile:

Thanks,
Austin

Austin
If you take a look at components I think you’ll find an even more
straightforward way of doing this that allows you to keep render calls
in the controller.

see the link below for the api docs about them, I think they’re neat.
http://api.rubyonrails.com/classes/ActionController/Components.html

Cheers,
Chuck V.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs