开发者

Difference between :class and :id , under what circumstances would we generally use <%= %> and <% %> in Rails

开发者 https://www.devze.com 2023-03-11 01:34 出处:网络
when we make use of rails helpers like form_form, form_tag, many a times especially when we need to use Javascript using the :html option that comes along with these helpers we give :id => \"some_v

when we make use of rails helpers like form_form, form_tag, many a times especially when we need to use Javascript using the :html option that comes along with these helpers we give :id => "some_value" and :class => "some_value". I just wanted to understand what separates the "id" and "class" from usability perspective. This would help me to better decide when I would need to use either of these options and when would I have to use both of them.

Also,

I just wanted to know exactly understand under what circumstances do we use <%= %> and when would we use <% %> wrt Rails. I have seen their use in a variety of circ开发者_JAVA百科umstances so far.

It would be great if you could answer these questions with relevant e.g.'s,

Many thanks for your time...


Your 'class' vs 'id' question is really referring to CSS best practices. Here's some info on that: http://css-tricks.com/the-difference-between-id-and-class/

The <%= %> ERB tag outputs the result of the expression in the tag, for example...

<%= ['hello', 'world'].join(' ') %>

Would be replaced with the string "hello world"

Lets say you want to set a variable for later use, for that you would use the <% %> tags because you don't want to output the result yet. Eg:

<% my_var = "test" %>

This outputs nothing, but does set the my_var variable for later use. If you used the <%= by mistake...

<%= my_var = "test" %>

That tag would be replaced with "test" in the resulting rendered page, which probably isnt what you wanted to do in that case. Another common use for <% %> tags are loops.

<% ['item1','item2','item3'].each do |item| %>
  <li><%= item %></li>
<% end %>

Which would result in:

<li>item1</li>
<li>item2</li>
<li>item3</li>

I hope this helps clear up some of your questions!


Another thing in Rails is that after 3.0 release helpers like form_for etc uses <%= %>, because it add tags for you in the background. (So since .each only prints the text/code in the block, it doesn't require the =)

So <%= %> evaluates the code in between, and then prints the result to your page, and <% %> just runs the code.

If you really need to print something within <% %>, use #concat

0

精彩评论

暂无评论...
验证码 换一张
取 消