Rails 3.1.4 - Render :text
Asked Answered
O

3

15

I'm updating my rails 2 apps to rails 3 and find that the use of 'render :text' does not behave the same anymore.

@results is an array. In my controller:

render :text => "<ul>#{@results}</ul>"

It's returning the whole array as a string rather than iterating through each value:

<ul>
  ["
  <li>Steve</li>
  ", "
  <li>John</li>
  "]
</ul>

Worked fine in Rails 2.x but not in 3. How do I fix this?

I'm expecting a result of:

<ul>
  <li>Steve</li>
  <li>John</li>
</ul>
Oxa answered 30/3, 2012 at 0:51 Comment(0)
L
34

I know this question is for Rails 3.1.4 only.

But those who come here and are on a more recent version, starting with Rails 5.1 we'll do this:

render plain: "I'm like everyone else."
Lamkin answered 14/4, 2018 at 8:49 Comment(1)
Nice. Note that this sets the Content-Type header to text/plain (among the charset). If you came here looking for how to render HTML (but not in a template file), use render html: '<div>...</div>'. That sets the header to text/html and your browser will know to parse the hTML. (Potentially call .html_safe on your html string, but be careful.)Bole
E
10

The string contains HTML tags so you will need to mark it as safe so that Rails doesn't escape the tags.

render :text => "<ul>#{@results}</ul>".html_safe

NOTE: Unless there is a valid reason to have HTML in your controller, I recommend moving the list items to a view.

6/23/2014 UPDATE: In retrospect, I don't like having this string parsing logic in the controller. The @results suggests there is HTML embedded in an object somewhere. I recommend using a presentation object and call a method like @results.list. The Draper gem is well-suited for this.

Cite

Eger answered 5/3, 2014 at 3:31 Comment(0)
S
2

I would suggest doing the following instead of render :text

render :partial => "result", :collection => @results

and add the file: _result.html.erb with

<ul>
  <%= result %>
</ul>

or even better if you can remove the li tags from @results

<ul>
  <li><%= result %></li>
</ul>

The Rails 3 docs say render text should be used for NON HTML text, which does not fit your use case. Using render :partial :collection is a better and more rails 3 way to iterate through your list.

Saval answered 30/3, 2012 at 2:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.