Russell
Russell

Reputation: 37

Append safe HTML to unsafe HTML in Rails 3.2

Suppose I have,

<%= @order.shipping.address1 + '<br />' unless @order.shipping.address1 %>
<%= @order.shipping.address2 + '<br />' unless @order.shipping.address2 %>

How can I return the variable with the default stripping of tags, and print the '
' as html_safe?

Presumably, wrapping in <%= raw ... %> would open up security issues with the variable not being stripped of html.

Upvotes: 0

Views: 281

Answers (1)

Milan K&#246;pke
Milan K&#246;pke

Reputation: 1133

You don't want to use anything like raw or html_safe because it opens up vulnerabilities in the adress fields as you are rightfully saying.

You can just rewrite it like this:

<% unless @order.shipping.address1 %>
  <%= @order.shipping.address1 %> 
  <br />
<% end %>
<% unless @order.shipping.address2 %>
  <%= @order.shipping.address2 %>
  <br />
<% end %>

But I would consider doing it with html/css instead of adding break lines. Surrounding it with a div will actually make the next element appear in the next line because a div is a block element and thus creates a line wrap.

View:

<% unless @order.shipping.address1 %>
  <div>
    <%= @order.shipping.address1 %> 
  </div>
<% end %>
<% unless @order.shipping.address2 %>
  <div>
    <%= @order.shipping.address2 %>
  </div>
<% end %>

If you need further styling you can add a class and use css for width, height and other stuff.

Upvotes: 1

Related Questions