Print in ERB without <%=?

前端 未结 3 1266
萌比男神i
萌比男神i 2020-12-14 00:57

Sometimes it\'s more convenient to print in <%%>. How to do it in Rails?

相关标签:
3条回答
  • 2020-12-14 01:45

    erb has two method to evaluate inline ruby expressions. The <% which evaluates the expression and the <%= which evaluates and prints. There is no global object to print to within the binding context.

    As mentioned by Omar, there is a concat method, which is part of ActionView. This will do what you want.

    Unlike a scripting language escape, there is no default output for erb. Since erb is simply a function, and given a template and binding will return a variable, it returns the values of text and functions recursively.

    There is hot debate as to how much logic should be allowed in a view, but as little as possible is what most people aim for. If you are putting more code than text in the view, you may want to consider refactoring your code.

    0 讨论(0)
  • 2020-12-14 01:54

    In ERB: The <% %> signify that there is Ruby code here to be interpreted. The <%= %> says output the ruby code, ie display/print the result.

    So it seems you need to use the extra = sign if you want to output in a standard ERB file.

    Otherwise, you could look at alternatives to ERB which require less syntax,.. maybe try something like HAML. http://haml-lang.com/tutorial.html

    Example:
    
    # ERB
    <strong><%= item.title %></strong>
    
    # HAML
    %strong= item.title
    

    Is that more convenient?

    0 讨论(0)
  • 2020-12-14 02:00

    http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-concat

    Should be what you are looking for.

    E.g. the following statement using concat:

    <% concat "Output" %>
    

    is equivalent to:

    <%= "Output" %>
    
    0 讨论(0)
提交回复
热议问题