How to avoid white in Rails?

I know that rails automatically elude characters like '<' or '&', but it does nothing for multiple spaces next to each other. I would like to avoid everything, including spaces.

I understand that usually you do not want to use &nbsp; , and you should use css instead. However, I am trying to accept user input and display it, so css is not possible.

For example, I have user input: test . When I show it with <% =@user _input%> in the view, extra spaces appear as one space (although it displays correctly in the source).

Is there an easy way to avoid spaces? Should I just use h @user_input and then replace all spaces?

+4
source share
1 answer

Spaces are not removed. Browsers simply interpret multiple whitespace as a single space.

You can convert each space to &nbsp; , if you want to:

 <%= raw @user_input.gsub(/\s/, "&nbsp;") %> 

Instead, you can replace each space with an empty <span class="whitespace"></span> , and then use CSS for the space character styles as you like.

Finally, you can do this with CSS only , using the white-space: pre style (example below).

Edit (to respond to a subsequent comment in your comment)

 <%= raw h("this is a sample & with ampersand.").gsub(/\s/, "&nbsp;") %> 

It speeds up & like &amp; in the source (and will be similar for other HTML objects) and then converts the " " to &nbsp; .

+9
source

All Articles