raw and html_safe method
They both are used to unescape the html from any string.For Example:-
In your helper method-
def raw_example()
raw "<b>Hello</b>"
end
In your view
<%= raw_example %>
Output:-
Hello
similarly for html_safe
def html_safe_example()
"<b>Hello</b>".html_safe
end
In your view
<%= html_safe_example%>
Making it safe from attacks
Suppose you are taking any content from the user then using it with the html_safe to unescape the html like this.
def html_safe_example(name)
"<b>Hello #{name}</b>".html_safe
end
Lets assume that the content here is "world" everything is good and will work fine. However you have made your site vulnerable to attacks.What if the user sends any html content instead of his name , suppose "<script>alert("attack")</script>.
To avoid this, instead of writing the whole html content in one line and do it step by step and dont make the name variable as html_safe like this:-
def html_safe_example(name)
html = "".html_safe
html << "<b>Hello".html_safe
html << name
html << name
html <<"</b>".html_safe
end
Make sure while concatenating that all the content are html_safe or they all are strings.Else it will give unexpected result.
Content_tag
content_tag returns the html tag of the name provided in the content_tag syntax.
For example:-
-> content_tag(:p, "hi") will return <p>hi</p>
-> content_tag(:div, content_tag(:p, "Hello world!"), :class => "strong")
No comments:
Post a Comment