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

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.

Related

Ruby on Rails - Underline words if they appear in dynamically generated text using Ruby

I am trying to underline words that are dynamically generated by the debug(params) method provided by rails. I have something below, but it obviously does not work, plus what I have below is attempt to try and change the words using methods that I already know about (like the .upcase method). I was hoping to underline the word controller if it appears in the text using only Ruby. Can anyone help me out here?
<%= debug(params) if Rails.env.development? %>
<% if debug(params).include?('controller:') %>
<%= 'controller'.upcase %>
<% end %>
thanks
edit:
I should add that debug(params) is a method defined by RAILS, I was able to do the following which seems even more off, so far the answers have not been correct to what I want to do.
<% if Rails.env.development? %>
<% debug_method = debug(params).split.each do |word| %>
<% if word == 'controller:' %>
<ul><% word.upcase %></ul>
<% end %>
<% end %>
<%= debug_method.join %>
<% end %>
which returns the following text: https://ibb.co/cvnEpw , keep the answers coming in though. I want to get the words in the original box (that's generated by the method to underline the controller word https://ibb.co/jmSm2G).
use <u></u> tag
<%= debug(params) if Rails.env.development? %>
<% if debug(params).include?('controller:') %>
<u><%= 'controller'.upcase %></u>
<% end %>
example here
Provide the css to generate html element:
p { text-decoration: underline; }
Add html elemnt to wrap your words:
<%= debug(params) if Rails.env.development? %>
<% if debug(params).include?('controller:') %>
<p> <%= 'controller'.upcase %> </p>
<% end %>
The answer to the question is below. I had to use the .gsub and .html_safe methods.
<%= debug(params).gsub("controller:", "<u>controller:</u>").html_safe %>
This code keeps the existing html & css generated by rails intact

Ruby when to use <% or <%= for opening [duplicate]

This question already has answers here:
What is the difference between <%, <%=, <%# and -%> in ERB in Rails?
(7 answers)
Closed 7 years ago.
Sorry I'm very new to Ruby and this is probably a simple question and I am just searching wrong for it.
For example:
<% flash.each do |key, value| %>
<%= content_tag :div, value, class: "alert alert-#{key}" %>
<% end %>
Why do we only use <% %> at the beginning and end of the loop, but <%= is used in the loop?
Another example, no loop involved:
<li><%= link_to "Contact Us", new_contact_path %></li>
Why am I using <%= instead of <% here?
Thanks for helping me with this newb question
You'll use <%= when you want the ERB to actually render code as a string in the browser, and <% when you simply want to execute Ruby code (e.g. performing an iteration, setting a variable, etc.)
In your examples:
<% flash.each do |key, value| %>
<%= content_tag :div, value, class: "alert alert-#{key}" %>
<% end %>
<% is used on flash.each to iterate over the flash variable, and then <%= is used to actually render a content_tag containing the values set when piping in key and value into the block.
Are you using erb?
<%> will execute the ruby code inside the brackets
<%=> will actually render some code in your view

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.

Printing elements of array using ERB [duplicate]

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 %>

When do you use <% -%> instead of <% %>

I've noticed that in some lines of rails views, this is used:
<% # Code... -%>
instead of:
<% # Code... %>
What is the difference?
<ul>
<% #posts.each do |post| -%>
<li><%=post.title%></li>
<% end -%>
</ul>
There will be no new lines in between the <ul> and first <li> and the last closing </li> and </ul>. If the - was omitted, there would.
The different options for evaluating code in ERB are as follows (they can be accessed in Textmate using Ctrl-Shift-. ):
<% %> Just evaluate the contents.
<%= %> Evaluate the contents and puts the result.
<%= -%> Evaluate the contents and prints the result.
<%# %> The contents is treated as a comment and not outputted.
Notice the difference between puts and print. Puts always adds a new line at the end of the string whereas print doesnt.
Basically, the -%> says don't output a new line at the end.
Consider this
<div>
<% if #some_var == some_value %>
<p>Some message</p>
<% end %>
</div>
The code above yields to the HTML below if the #some_var is some_value
<div>
<p>Some message</p>
</div>
If you've put - in the closing tag, then the ERB interpreter would remove the new lines for those with code tag including - and result in the following
<div>
<p>Some message</p>
</div>
This is useful if you need to have a good looking code for HTML. Sometimes you'll find it useful when working sideby side with a designer
Hope this helps.
A little late, but I think it's worth pointing out that you can also do this:
<%- #posts.each do |post| -%>
<li><%= post.title %></li>
<%- end %>
This strips away any whitespace in front.

Resources