Shao Kahn
Shao Kahn

Reputation: 77

Rails -- h.simple_format fix

This is my code:

 = h.simple_format(item.text.text, class: 'basic')

And item.text.text is "<p><span style=\"color: rgb(251, 213, 181);\">asdasdasd</span></p>", but when I see the view which was rendered in inspect, the style=\"color: rgb(251, 213, 181);\" attribute goes away!

How to fix this! (Note: I need class: 'basic'!)

Upvotes: 0

Views: 918

Answers (1)

Leo
Leo

Reputation: 1773

simple_format from ActionView::Helpers::TextHelper has default option sanitize: true

Sanitizes the html by converting and tags into regular text, and removing all "onxxx" attributes (so that arbitrary Javascript cannot be executed). It also removes href= and src= attributes that start with "javascript:". You can modify what gets sanitized by defining VERBOTEN_TAGS and VERBOTEN_ATTRS before this Module is loaded.

To prevent deleting style attribute:

simple_format(item.text.text, { class: 'basic' }, sanitize: false)

<p> inside <p> is invalid in all standards of HTML because the opening <p> tag will automatically close the <p> element:

#item.text.text => "<p><span style=\"color: rgb(251, 213, 181);\">asdasdasd</span></p>"

simple_format(item.text.text, { class: 'basic' }, sanitize: false, wrapper_tag: "div")
#=> "<div class=\"basic\"><p><span style=\"color: rgb(251, 213, 181);\">asdasdasd</span></p><div>"

Upvotes: 1

Related Questions