Enter a line break in the form
Line breaks are not reflected when outputting
macOS Catalina 10.15.6
ruby 2.6.5
Rails 6.0.3.4
MySQL : 5.6.47
Bootstrap : 4.3.1
simple_format: Helper method. Line breaks are represented by p tags and br tags
h option: XSS countermeasures. Add escape function to simple_format
【reference】
app/controllers/tasks_controller.rb
def show
@task = Task.find(params[:id])
@commits = @task.commits
end
erb:app/views/tasks/show.html.erb
<% @commits.each do |commit| %>
<%= commit.content %>
<% end %>
With this display method, line breaks in commit.content are not reflected.
This can be solved by using simple_format. Let's actually do it.
erb:app/views/tasks/show.html.erb
<!-- simple_use format-->
<% @commits.each do |commit| %>
<%= simple_format(commit.content) %>
<% end %>
** simple_format is a helper method ** that expresses line breaks with p tags and br tags. Just put the text you want to output in simple_format and you're done.
Well, for the time being, the goal is achieved. However, there is a problem with this implementation. It is not "escaped" </ b>.
Let's take a closer look.
Escape is a technique used in security measures. Simply put, it has the role of " eliminating the meaning of meaningful characters </ b>".
Let's look at it concretely. For example, suppose you enter the following.
If you display this value without escaping it, it will be recognized as an "HTML tag" like this.
In HTML, "<" is recognized as meaning "tag starts!". Therefore, if it is not escaped, it will be displayed as an h1 element.
This escape feature is granted by using <% =%> used in Rails views. However, if you use simple_format, you lose this functionality.
Therefore, when using simple_format, use the h option. This is a great way to add an escape feature to simple_format.
erb:app/views/tasks/show.html.erb
<%#use h option%>
<% @commits.each do |commit| %>
<%= simple_format(h(commit.content)) %>
<% end %>
This will change the display as shown below.
The meaning is deprived from "<" etc., and it is displayed as a simple symbol or character. Along with that, the letters have become smaller! (Enclosed in p tag)
I want to reflect the line break of form
Possible with simple_format!
Better to use h for security measures
It seems that simple_format is often used, but it is also a scary helper method if security measures are neglected. When using it, keep it in mind.
Recommended Posts