Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails ERb best practices (<% %> vs <% -%> vs <%- -%>)

Tags:

What is the recommended use of ERb in Rails when it comes to <% %> (evaluate Ruby code), <% -%> (evaluate Ruby code, suppress the trailing newline) and <%- -%> (evaluate Ruby code, suppress the trailing newline and leading space)? It seems like <%- -%> would make the output HTML look nicest, but <% %> seems to be mostly what I see.

like image 361
jrdioko Avatar asked Nov 08 '10 19:11

jrdioko


People also ask

What does ERB stand for in File_name ERB?

ERB stands for Embedded Ruby.

What is <% in Ruby?

Tags. ERB has two tags for Ruby code, a tag for comments, and a way to escape tag delimiters. <%= EXPRESSION %> — Inserts the value of an expression. With -%> — Trims the following line break.

What are ERB files used for?

What is a ERB file. ERB files contain source code written in a programming language of the same name. The ERB language is essentially a Ruby templating language. ERB files are saved in a plain text format which allows them to be opened in any text editing program.

What are the necessary steps to get from file ERB to file HTML?

The ruby ERB library operates on strings, so you would have to read the . erb file into a string, create an ERB object, and then output the result into an html file, passing the current binding to the ERB. result method. where @my_erb_string .


2 Answers

It's a personal preference. I use <% %> when I'm writing a loop or a block, because I want new lines there. I use <% -%> in rare cases of variable assignment. And I never use <%- -%> because that's one option too many.

like image 90
marko Avatar answered Oct 02 '22 13:10

marko


I just read in http://ruby-doc.org/ruby-1.9/classes/ERB.html that you can even use a single percent sign for oneliners (if there is nothing else on that line)

Example from the docs:

<%# ignore numerous minor requests -- focus on priorities %>
% priorities.each do |priority|
  * <%= priority %>
% end

aaaalmost like HAML, isn't it? :)

like image 43
onetom Avatar answered Oct 02 '22 14:10

onetom