What is the difference between <%, <%=, <%# and -%> in ERB in Rails?

前端 未结 7 1623
一向
一向 2020-11-21 05:33

Can some one please describe the usage of the following characters which is used in ERB file:

<%   %>
<%=  %>
<%  -%>
<%#  %>
         


        
7条回答
  •  余生分开走
    2020-11-21 05:54

    <% %> executes the code in there but does not print the result, for eg:
    We can use it for if else in an erb file.

    <% temp = 1 %>
    <% if temp == 1%>
      temp is 1
    <% else %>
      temp is not 1
    <%end%>  
    

    Will print temp is 1


    <%= %> executes the code and also prints the output, for eg:
    We can print the value of a rails variable.

    <% temp = 1 %>
    <%= temp %>  
    

    Will print 1


    <% -%> It makes no difference as it does not print anything, -%> only makes sense with <%= -%>, this will avoid a new line.


    <%# %> will comment out the code written within this.

提交回复
热议问题