开发者

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

开发者 https://www.devze.com 2023-01-20 02:43 出处:网络
This question already has answers here: What is the difference between <%, <%=, <%# and -%> in ERB in Rails?
This question already has answers here: What is the difference between <%, <%=, <%# and -%> in ERB in Rails? (7 answers) Closed 8 years ago.

i fou开发者_高级运维nd 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?


<% %>

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


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


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

精彩评论

暂无评论...
验证码 换一张
取 消