Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

<% %>(without equal) in ruby erb means? [duplicate]

i found this "executed with no substitution back into the output" , but maybe my English wasn't too good , i cant really understand what it means. Can anyone help out?

like image 529
wizztjh Avatar asked Oct 17 '10 07:10

wizztjh


People also ask

What does ERB mean in Ruby?

ERB (Embedded RuBy) is a feature of Ruby that enables you to conveniently generate any kind of text, in any quantity, from templates. The templates themselves combine plain text with Ruby code for variable substitution and flow control, which makes them easy to write and maintain.

How do ERB files work?

An ERB object works by building a chunk of Ruby code that will output the completed template when run. If safe_level is set to a non-nil value, ERB code will be run in a separate thread with $SAFE set to the provided level. eoutvar can be used to set the name of the variable ERB will build up its output in.

What does ERB stand for in File_name ERB?

ERB stands for Embedded Ruby.

How do you comment on ERB?

erb is by definition "embedded ruby", you can embed every ruby code between: <%= and the other: %> , typically all written in one line. In addition, ruby one-line comments start always with # , so the <%=# Comment %> style matches perfectly with both pure-ruby and erb styles for one-line comments.


3 Answers

<% %>

Will execute Ruby code with no effect on the html page being rendered. The output will be thrown away.

<%= %>

Will execute Ruby code and insert the output of that code in place of the <%= %>

example...

<% puts "almost" %> nothing to see here 

would render as

nothing to see here

however

<%= puts "almost" %> nothing to see here

would render as

almost nothing to see here
like image 168
Michelle Six Avatar answered Oct 01 '22 00:10

Michelle Six


Sometimes you will have to (or you want to) execute some ruby statements but not for output purpose.

like the following:

<% if @user.nil? %>
  Hi, welcome!
<% else %>
  Hi, <%= @user.name %>!
<% end %>

Of course this is just one use case, but sometimes you do need <% %> :D

like image 27
PeterWong Avatar answered Sep 30 '22 22:09

PeterWong


Code in <% %>(without equal) is executed "with no substitution back into the output" means you want to execute code WITHOUT any output, like a loop and the best part is, it can be used with a non ruby code.

<% 3.times do %>

<h1>Hello world</h1>

<%end%>

This will give:

<h1>Hello world</h1>  
<h1>Hello world</h1>  
<h1>Hello world</h1>  
like image 37
zengr Avatar answered Oct 01 '22 00:10

zengr