1

I am using Ruby on Rails 3.2.13 and I would like to render partial templates for an array of objects within a helper method. That is, in my helper file I have:

def render_articles(articles)
  articles.each do |article|
    render :partial => ...
  end
end

The above method, however, doesn't return partial templates but an array. How can I properly render those?

1
  • 1
    why not just render :partial => '...', :collection => articles? Commented Sep 20, 2013 at 18:00

1 Answer 1

1

The each block you have doesn't return the contents of the block but rather returns the array itself. You need a mechanism to return the contents.

A method:

def render_articles(articles)
  html = ""
  articles.each do |article|
    html += render :partial => ...
  end
  html.html_safe
end

Another method:

def render_articles(articles)
  articles.inject("") { |html, article| html + render :partical =>... }.html_safe
end
Sign up to request clarification or add additional context in comments.

6 Comments

By using your code I get the plain text of partial templates and that text is not rendered as HTML code, unless I use html_safe method. But, generally speaking, is it dangerous to use the html_safe method?
@user502052 You have to use html_safe. It's not dangerous in this context.
You can also do, shorter : articles.map { |article| render partial: ... }.join('').html_safe
@Olivier El Mekki - Out of curiosity, what is the most performant method between the two proposed solutions (inject and map)?
#map is slightly more efficient, but only with high computation : gist.github.com/oelmekki/6f5fcc120e052a84ffdd . This should not make any difference in your case (unless you generate 10 000 partials, and then that would not be your worse problem :) )
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.