Luke
Luke

Reputation: 23680

Looping through a list of objects within View and printing values with a single <%=

I'm looping through a list of objects using the following code within my View:

<% @myquiz.each do |x| %>
    <div id="myDiv">
        <%= x.quiz_ID %>
    </div>
<% end %>

This works fine, it prints the IDs on to the page. However I feel that it would be cleaner if I didn't have to put so many sets of <%s and <%=s

The following would be preferable, but it doesn't work:

<% @myquiz.each do |x|

    render :text "<div>#{x.quiz_ID}</div>"

end %>

Is there a way to put information on to the screen within a loop like above, without having 3 sets of <% tags? and another <% tag for each subsequent value that I want to show on the page.

Upvotes: 1

Views: 3044

Answers (3)

Thomas Klemm
Thomas Klemm

Reputation: 10856

Here are a few hints, merely to give a few pointers on Ruby methods.

# Original
<%= @myquiz.each do |x|
    puts "<div>" . x.quiz_ID . "</div>"
end %>

<%= expression %> will cause the expression to be visible in the HTML. Thus you'll have to manipulate the return value of your expression. You're using .each there, while for this purpose .map is more suitable, as it will return an array with the output of the block for each input variable.

In the block the last statement is the return value, no need to print stuff someway.

In the end, an array like ['A', 'B', 'C'] will still want to be joined by some line breaks stuff, so the expression would need to be joined with .join('<br />').

This is a hell of a mess, but anyway, here it is:

<%= @myquiz.map {|x| "<div>#{ x.quiz_id }</div>" }.join("<br />").html_safe %>

# or

<%= @myquiz.map(&:quiz_id).map { |id| "<div>#{ id }</div>" }.join("<br />").html_safe %>

Don't do this at home. Seriously. Just note how .map works, how it collects return values (the last statement), and how to join array elements to form a string.

Further options:

What would DHH do? Presumably go with the extra brackets, or move the logic somewhere else (into a helper or decorator) and just output some kind of <%= quiz_results %>.

What would I do? Take a look at Slim and slim-rails for integrating it and auto-generating .html.slim views.

# In a slim view
- @quizzes.each do |quiz|
  div = quiz.id

Upvotes: 1

Kiattisak Anoochitarom
Kiattisak Anoochitarom

Reputation: 2157

do block with curry brackets

<%= @myquiz.each { |x| puts x.quiz_ID } =%>

if statement in block has more than 2 you should write block with 'do-end', that's right.

Upvotes: 0

Christoph Geschwind
Christoph Geschwind

Reputation: 2680

<%= @myquiz.map(&:quiz_ID).join(', ') %>

Upvotes: 3

Related Questions