Printing elements of array using ERB [duplicate] - ruby-on-rails

This question already has answers here:
What is the difference between <%, <%=, <%# and -%> in ERB in Rails?
(7 answers)
Closed 3 years ago.
I'm trying to print a simple array defined in my controller into my view with a new line for each element. But what it's doing is printing the whole array on one line.
Here's my controller:
class TodosController < ApplicationController
def index
#todo_array = [ "Buy Milk", "Buy Soap", "Pay bill", "Draw Money" ]
end
end
Here's my view:
<%= #todo_array.each do |t| %>
<%= puts t %><\br>
<% end %>
Here's the result:
<\br> <\br> <\br> <\br> ["Buy Milk", "Buy Soap", "Pay bill", "Draw Money"]

Erb, the templating engine you're using in your views, has a few different ways of embedding ruby code inside templates.
When you put code inside <%= %> blocks, erb evaluates the code inside and prints the value of the last statement in the HTML. Since .each in ruby returns the collection you iterated over, the loop using <%= %> attempts to print a string representation of the entire array.
When you put code inside <% %> blocks, erb just evaluates the code, not printing anything. This allows you to do conditional statements, loops, or modify variables in the view.
You can also remove the puts from puts t. Erb knows to try to convert the last value it saw inside <%= %> into a string for display.

Hey why are you putting '=' sign in first line. <% %> are used for telling rails that string under this is ruby code,evaluate it. Where as <%= %> this tells rails that string in these tags is in ruby, evaluate it and print the result in html file too.
Hence try to inspect your code you are writing
<%= #todo_array.each do |t| %>
while this line is only for iterating over #todo_array hence we wont be in need to print that line. So final code should be
<% #todo_array.each do |t| %>
<%= puts t %>
<% end %>

Just try:
<%= #todo_array.join('<br />').html_safe %>
instead of
<%= #todo_array.each do |t| %>
<%= puts t %><\br>
<% end %>

Two issues with your view:
you are using "<%=" where you should be using "<%".
you don't need 'puts'
This should improve your results:
<% #todo_array.each do |t| %>
<%= t %><\br>
<% end %>
I would further consider using some HTML structure to better structure your todo list (instead of using br tag at the end of lines), perhaps an un-ordered list like so:
<ul>
<% #todo_array.each do |t| %>
<li><%= t %></li>
<% end %>
</ul>

Remove the equal sign from your each statement:
<% #todo_array.each do |t| %>
<%= t %><\br>
<% end %>

Related

Rails different output if block is given inline or over multiple lines

I'm having trouble finding out what I did wrong or how to achieve the same result.
What I'm trying to do is to print the array #attributes in a rails view.
This is not working:
<% #attributes.each do |element| %>
<%= puts element.to_s %>
<% end %>
But this is:
<%= #attributes.each { |element| puts element.to_s }%>
I've also played around with putting everything in the first statement in <%= %> without any success.
Aren't those two statements exactly the same?
Also, if you could help me out - how would you iterate over the array and insert a new line after each item?
Thanks in advance!
Alex
puts does not actually output to the ERB buffer. It outputs to STDOUT and returns nil. If you want to iterate through the records and output you would do it by:
<% #attributes.each do |element| %>
<%= element.to_s %>
<% end %>
The <%= %> ERB tags output the return value of the expression into the buffer. If you wanted to do this with a non-printing ERB expression you would need to use concat:
<% #attributes.each { |element| concat element.to_s } %>
Aren't those two statements exactly the same?
No. The output is actually the same as:
<% #attributes.each do |element| %>
<%= nil %>
<% end %>
And
<%= #attributes %>
Rails uses the ERB templates to render the views or say generate html documents for the browsers amongst others.
ERBcopies the text portions of the template directly to the generated document, and only processes code that is identified by markers. There are mostly two types of markers <% %> and <%= %>.
A tag with an equals sign indicates that the enclosed code is an expression and that the renderer should substitute the code element with the result of the code (as a string) when it renders the template.
Tags without the equals sign denote that the enclosed code is a scriptlet. Each scriptlet is caught and executed, and the final result of the code is then injected into the output at the point of the scriptlet.
<% #attributes.each do |element| %>
<%= puts element.to_s %>
<% end %>
With your example above you're telling the renderer to put whatever is the result of the expression in the second line, which is the output of the element.
Whereas here <%= #attributes.each { |element| puts element.to_s }%> you are asking rendered to put the #attributes object/variable along with the individual output of whatever is inside in #attributes variable which explains the difference in your output results.
PS you can avoid both puts and to_s from <%= puts element.to_s %> because whatever is inside <%= %> gets to the HTML document as a string itself.

What is the difference between <%= and the "puts" command in rails?

I have a segment of code:
<% #public_address.each do |key| %>
<%= key["address"]["address"] %>
<% end %>
This displays the keys properly, but this code
<% #public_address.each do |key| %>
<% puts key["address"]["address"] %>
<% end %>
displays nothing. What gives? What's the difference between the two?
The <% %> and <%= %> are used in erb to execute ruby code when rendering a template.
Erb is the default template engine in rails.
Difference between <% %> and <%= %>
<% %> Will evaluate the ruby code it contains, but "silently".
Meaning that no output is going to be printed on the rendered page.
<%= %> on the other end, evaluates the ruby it contains and
renders the result on the rendered page.
What's the difference between <% code %> and <%= code %> in Rails erb?
What's puts?
Puts is simply a method from Ruby that is used to print a string at runtime. It has nothing to do with erb templates.
In your first bit of code <%= key["address"]["address"] %>, the <%= %> is rails syntax for evaluating the code inside and returning the value.
In your second bit of code <% puts key["address"]["address"] %>, you use <% %>, which doesn't return an evaluated rails statement. Furthermore, puts is a method that outputs whatever follows it to the stout object. In a command line program, that means printing out to the terminal screen, but in a web app you aren't working with a terminal screen. You are working with controllers and view templates, so it is necessary to use the evaluative <%= %> if you want to return values that will be displayed in the view.

In a rails view, how can I send output to view besides <%= %>?

Short version:
It seems weird to me to have rails code like, say,
<% if #list.empty
%><%= val %><%
end %>
Is there some way to do something like this?
<% if #list.empty
some_display_function_i_wish_existed val
end %>
Long version:
I have a model, tweet.rb, that overrides to_s. The to_s works fine.
I have a view that needs to output to_s for each tweet in #meme.tweets .
I've observed the following:
<% #meme.tweets.each do |tweet|
tweet
end %>
Result: no output
<% #meme.tweets.each do |tweet|
puts tweet # or tweet.to_s does the same thing
end %>
...Result: no output
<%= #meme.tweets.each do |tweet|
tweet
end %>
...Result: output is entire inspection of each tweet, not to_s
<%= #meme.tweets.each do |tweet|
puts tweet # or tweet.to_s does the same thing
end %>
...Result: output is entire inspection of each tweet, not to_s
<% #meme.tweets.each do |tweet| %>
<%= tweet %>
<% end %>
...Result: works as intended (outputs result of to_s for each tweet). So does:
<%= #meme.tweets.collect do |tweet|
tweet.to_s
end %>
...Result: works as intended.
I come from a PHP background, and don't really understand the rules here.
I know I can do it the way I did in the last example.
But could someone explain why none of the other examples work as I intend?
It seems to me that the rules APPEAR to be:
1) <%= something %> will take that thing, call to_s on it, which will default to inspect if not overridden.
2) <% something %> will execute something
Is there a way to use 2) <% %> to send output to the view?
Or is it against the rules to have <% %> tags that span multiple lines of ruby code at all?
<%= code %> will print to the the output the result of the inner code. <% %> won't print anything, it just evaluates the inner code.
That's why the first example doesn't work. On the second example you expect the puts to print the tweets, but puts doesn't print on the same buffer... (you'll see the tweets printed on the rails console instead).
On 3rd and 4th example you are printing the collection as an object (#meme.tweets.each returns an Enumerable and ERb call #to_s on that) and not the code inside the block.
The 5th form is correct. That's what you'll normally do.
The 6th form is in some way correct too. There you are iterating a collection, calling #to_s on each element and then collecting them on a new array, that gets printed to the output (but you are printing an array of strings, not just one big string).
you can get a similar result with #join. (It returns a string created by converting each element of the array to a string)
<%= #meme.tweets.join %>
<% %> are used when you do not want the Ruby code you're executing to output anything. The <%= %> tags are used when you want to output something. This is why your example using <%= %> and tweet.to_s works as intended.
If you don't specify which attribute you want to output, then yes, puts will display the whole object. If for example, you had a message attribute on your tweet object, writing tweet.message (inside of a <%= %>, of course) would output just the message attribute of that tweet.
The direct answer is the concat function, eg:
Hi, my name is <% concat("Shelvacu") %>.
which is the same as
Hi, my name is <%= "Shelvacu" %>.
Which both output Hi, my name is Shelvacu.
Think of it like this: An erb template is parsed, transformed into valid ruby code, and then that ruby code is run*. Everything that is not inside <% ... %> is converted to concat("..."), <% statement %> is converted to statement, and <%= statement %> is converted to concat(statement.to_s).
So when ERB sees
1 + 2 = <%= 1 + 2 %>
<% puts "hello" %>
<% #meme.tweets.each do |tweet| %>
<%= tweet %>
<% end %>
that code is then translated to*
concat("1 + 2 = ")
concat((1 + 2).to_s)
concat("\n\n")
puts "hello"
concat("\n\n")
#meme.tweets.each do |tweet|
concat(tweet.to_s)
end
* This is an oversimplification, ERB does much more so that errors point the right line, statements don't merge with eachother in unexpected ways, and I didn't even mention <%- ... %>. However, this should be a decent mental model for understanding whats happening when you write code in ERB.

Why many people use "-%>" instead of "%>" in Rails? [duplicate]

This question already has answers here:
What is the difference between <%, <%=, <%# and -%> in ERB in Rails?
(7 answers)
Closed 8 years ago.
Sorry for this question, i think its more offtopic, but i couldn't find anything on google!
I saw now multiple times that a lot of people use -%> instead of just %>. Whats the sense?
Example:
<% #images.each_slice(6) do |slice| -%>
<div class="gallery">
<% slice.each do |image| -%>
<%= image_tag(image.url, :alt => image.alt) %>
<% end -%>
</div>
<% end -%>
Source: Rails each loop insert tag every 6 items?
Here he has also used -%> for all blocks.
I would like to add some resources that I know about ERB :
Rails extends ERB, so that you can suppress the newline simply by adding a trailing hyphen to tags in Rails templates:
<ul>
<% for #item in #items -%>
<li><%= #item %></li>
<% end -%>
</ul>
Comment markers use a hash sign:
<%# This is just a comment %>
A tag with an equals sign indicates that enclosed code is an expression, and that the renderer should substitute the code element with the result of the code (as a string) when it renders the template. Use an expression to embed a line of code into the template, or to display the contents of a variable:
Hello, <%= #name %>.
Today is <%= Time.now.strftime('%A') %>.
With one equal sign the string will be encoded. To avoid encoding, you can use two equals signs (or raw):
Hello, <%== #unencodedOutput %>
Tags without the equals sign denote that the enclosed code is a scriptlet. Each scriptlet is caught and executed, and the final result of the code is then injected in to the output at the point of the scriptlet.
<ul>
<% for #item in #shopping_list %>
<li><%= #item %></li>
<% end %>
</ul>
Scriptlets are most commonly used for embedding loops or conditional logic into templates:
Read An Introduction to ERB Templating to know more.

Rails - Display inline rails errors

How can I condense my code into a single statement:
<% #policyholderdetail.errors.each do |attr,msg| %>
<% if attr == :title %>
<li><%=attr %> <%= msg %></li>
<% end %>
<% end %>
I would like to show only the errors for :title next to the field but feel there should be a better statement to do this as opposed to looping through all of the errors until I get to the one I want.
Question - can I condense the first two lines into one better statement?
You can write: #policyholderdetail.errors[:title]. See here.
Use
<% if #policyholderdetail.errors[:title].present? %>

Resources