Unable to understand as to why we use html_safe than the conventional html to be rendered.
def group(content)
html = "".html_safe
html << "<div class='group'>".html_safe
html << content
html << "</div>".html_safe
html
end
I agree html_safe
doesn't make much sense in this example because content_tag
would be much shorter, easier to read and would automatically escape the user input:
def group(content)
content_tag(:div, content, class: 'group')
end
In Rails HTML ERB templates, strings passed into it are HTML escaped (to prevent Cross Site Scripting, which is injecting HTML code into your string so that attackers can execute JavaScript on visitors of your site). However, sometimes we know that our string is safe for HTML and don't want it to be escaped so that the HTML can actually be rendered. We do this by calling .html_safe
on a string to mark it as being safe for HTML rendering. You generally want to avoid using this as much as possible since it makes it easier to make a mistake and cause XSS to be a possible attack on your site.