Skip to content

Instantly share code, notes, and snippets.

@oojikoo-gist
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oojikoo-gist/ec20d5e2743d5e8c52e2 to your computer and use it in GitHub Desktop.
Save oojikoo-gist/ec20d5e2743d5e8c52e2 to your computer and use it in GitHub Desktop.
rails: run code in a view using ERB

Run code in a view using ERB:

  • <% ... %>: Run the code, but don’t print anything. Used for if/then/else/end and array.each loops. You can comment out sections of HTML using <% if false %> Hi there <% end %>. You get a free blank line, since you probably have a newline after the closing %>.

  • <%- ... %>: Run the code, and don’t print the trailing newline. Use this when generating XML or JSON when breaking up .rhtml code blocks for your readability, but don’t want newlines in the output.

  • <%= ... %>: Run the code and print the return value, for example: <%= @foo %> (You did remember the @ sign for controller variables passed to the view, right?). Don’t put if statements inside the <%=, you’ll get an error.

  • <%= h ... %>: Print the code and html escape the output: > becomes >. h() is actually a Ruby function, but called without parens, as Rubyists are apt to do.

It’s a bit confusing when you start out — run some experiments in a dummy view page.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment