← homeProgramming (Програмування)

What is the difference between <%, <%=, <%# and -%> in ERB templates (Ruby on Rails)?

What is the difference between <%, <%=, <%# and -%> in ERB templates (Ruby on Rails)? Examples of constructions.

This content has been automatically translated from Ukrainian.
In ERB (Embedded Ruby, *.erb files) templates used in Ruby on Rails, there are tags that define different types of embedded code: 
<%
<%=
<%#
-%>
They have the following meanings:
  • <% - this tag is used to insert Ruby code without outputting the result. It is used for logic and conditional expressions. For example, you can use it to create a loop or a conditional statement without directly outputting the result.
  • <%= - this tag is used to insert Ruby code with outputting the result. It is used to insert the value of a variable or the result of an expression directly into the output HTML code. For example, you can use it to display the value of a variable on the page.
  • <%# - this tag is used to ignore Ruby code (ERB comment) during the execution of the template. Everything between <%# and %> will be ignored and not outputted in the resulting HTML code. This is useful when you want to leave comments or temporarily disable a certain part of the code (during debugging).
For example:
<% if condition %>
  <%= variable %>
<% else %>
  <%# commented part %>
<% end -%>
  • -%> - This tag is used to control the whitespace after the closing tag. It is used to remove extra spaces or newline characters that are usually added after the tag %>
For example:
 <% 1 + 1 -%>
will output `2` without adding a space or newline character after it.
Tips:
<% %>  : Executes Ruby code
<%= %> : Outputs the given value in the ERB template
<% -%> : Removes spaces or newline characters after the expression
<%# %> : Commenting code

🔥 More posts

All posts
Programming (Програмування)May 16, '23 20:02

What is Origin in Git?

What is Origin in Git? Why write origin in a git command? When and why are aliases needed in git ...

Programming (Програмування)May 23, '23 06:57

What is debugging?

What is debugging?

Programming (Програмування)Jun 2, '23 12:53

What does super do in Ruby?

What does super do in Ruby? An example of using super in Ruby methods.