开发者

Rails embedding syntax doubt

I have been working ROR now.. I am very new to ROR..

Could anyone tell me of what is the difference between <%= %> and <%=h %>

why we have h here ??

in some cases i have seen t instead o开发者_Go百科f h..

Please clarify me


Everything between <%= and %> is evaluated as Ruby code, and the resulting string is inserted in the document (that's actually ERb and it can be used for arbitrary documents, not just HTML). And in this case it calls a method called simple h which escapes its argument. So I guess what you're seeing is more likely to be something like <%=h @somevar%>. So the content of @somevar is escaped by the method h, and the return string is inserted at the place of this whole expression.

The other ERb syntaxes that exist are <% ... %> to evaluate Ruby code but without inserting the result into the document, and then there's also <% ... -%> and <%= ... -%> to suppress a subsequent newline, thus avoiding gaps in the rendered document.


The <%=h %> syntax escapes characters that otherwise would mess up your page (e.g. '&'). It is actually a helper method called 'h'. So:

<%=h "Ann & Bill" %> 

will expand to Ann &amp; Bill whereas

<%= "Ann & Bill" %>

will expand to Ann & Bill, which might not be what you want in your HTML.


Now that Rails 3 has been released, be aware that the default behaviour from here on in is to automatically escape everything inside <%= %> tags. So XSS (Cross-site scripting) protection is always on, making the use of <%=h %> redundant. This might bite you if/when you upgrade your apps from Rails 2.

This Railscast (http://railscasts.com/episodes/204-xss-protection-in-rails-3) gives a nice primer on the above.

If you want this behaviour in your Rails 2.3 apps, you can use http://github.com/rails/rails_xss (for 2.3.8) or http://github.com/NZKoz/rails_xss (for 2.3.5)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜