Topic: Difference between <% and <%=

As the title says really... whats the different, if any, between the two?

Thanks

Re: Difference between <% and <%=

with <%= you print something to the place where you write it, while <% won't.

eg. <p><% "test" %></p> in in rhtml file will result in <p></p>
while <p><%= "test" %></p> will result in <p>test</p>

I hope thats understandable.

My homepage: http://www.komendera.com/
Working at: http://www.abloom.at/
My blog: soaked and soaped http://soakedandsoaped.com/

Re: Difference between <% and <%=

So one would use <% %> to execute some code in a view than?

Re: Difference between <% and <%=

Yep. You can execute code inside of <%= %> too, it's just going to echo any output to the browser.

Basically, any time you need to tell the user soemthing, use <%= %> otherwise, stick with <% %>.

If you're familiar with PHP, it's the same as using PHP's <?=$var;?> echo shortcut, rather than <? echo $var; ?>

Re: Difference between <% and <%=

Thanks - makes sense smile

Re: Difference between <% and <%=

Just a little gotcha: If you're using start_form_tag and end_form_tag helper methods, you use <%= for those:

<%= start_form_tag %>
....
<%= end_form_tag %>

This is because these methods are just spitting out open and closing form tags. But, if you use form_for method, you use <% like this:

<% form_for do |f| %>
....
<% end %>

Because form_for uses a block, it is doing more magic and not directly spitting out simple start and end form tags. Just keep this in mind, if you have a loop or a block, you usually don't use <%=.

Edit: oh, unless it's all on one line like this:

<%= @comments.collect { |c| "<p>#{c.body}</p>" } %>

But that usually isn't done.

*sigh* now I probably just confused you, sorry. smile

Last edited by ryanb (2006-09-02 12:07:23)

Railscasts - Free Ruby on Rails Screencasts

Re: Difference between <% and <%=

Just thought I'd add <% and -%>

Adding the - before the closing %> will make ERb remove the new line which would normally come next.

Re: Difference between <% and <%=

Thanks shadow! I've always asked myself what the -%> means :-)

My homepage: http://www.komendera.com/
Working at: http://www.abloom.at/
My blog: soaked and soaped http://soakedandsoaped.com/