Ruby when to use <% or <%= for opening [duplicate] - ruby-on-rails

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

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

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.

How do you pass local variables to a content_tag or content_for?

In my view, I have a content_tag that looks like so:
<% content_tag :div do %>
<h1><%= title %></h1>
<p><%= description %></p>
... # a bunch of other stuff
<% end %>
I'd like to use this content_tag multiple times to create "sections" on the page, each time passing a different title and description to it. However, I don't want to go and make a partial, that seems like overkill. I want everything to be contained in the one view file. How can I do it?
Assigning the content_tag to a variable (and subsequently printing the variable) seems a bit convoluted, particularly as there's no good way of passing your collection of products to it.
A DRYer way of doing this would be to iterate through your list of products and pass each to your content_tag:
<% products.each do |product| %>
<%= content_tag :div, :class => "product-info" do %>
<h1><%= product.name %></h1>
<p><%= product.description %></p>
<% end %>
<% end %>
Alternatively, you can abstract this logic into a view helper that effectively produces the same result:
def product_info_div(products)
products.each do |product| %>
content_tag :div, :class => "product-info" do %>
content_tag :div, product.name
content_tag :p, product.description
end
end
end
In your view, you'd invoke this in the following manner:
<%= product_info_div(#products) %>
While this isn't a partial, it is another file. However, it's also precisely what view helpers are meant to do. Either option will keep your code DRY and readable while accomplishing precisely what you want, IMO.
EDIT:
You don't need to explicitly pass local variables in order to use them within a content_tag – they're available for use within the content_tag as they'd be outside of it.
Though I'm unsure how you're precisely getting title and description to vary, you could make a parallel assignment directly prior to the content_tag declaration in which you assign values to the title and description local variables:
<% title, description = 'title_1', 'description_1' %>
<%= content_tag :div do %>
<h1><%= title %></h1>
<p><%= description %></p>
# a bunch of other stuff
<% end %>
<% title, description = 'title_2', 'description_2' %>
<%= content_tag :div do %>
<h1><%= title %></h1>
<p><%= description %></p>
# a bunch of other stuff
<% end %>
Note that you'll need to output the content_tag using <%= %>. Rails can't do anything with an interpreted content_tag if it's not outputted.

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

Why the use of both <% and <%= in the views?

If I write something like:
<% if signed_in?.blank? %> or <%= link_to "Sign Up", sign_up_path %>
What is the difference between the two signs of <% and <%=?
Why make it this way instead of using just one for simplicity?
When do I know I need to use <% over <%=?
<%= puts the return value of the code inside to the page.
<% just execute code.
Here is the good guide about ERB http://api.rubyonrails.org/classes/ActionView/Base.html
<% %> Simply executes the statement(s) inside that block, whereas <%= %> will output the result of the statement.
So for example, with the <% if signed_in?.blank? %>, the ruby interpreter just executes that code and checks if signed_in is blank.
The <%= link_to %> statement will actually generate HTML.

Resources