paris
paris

Reputation: 189

How do I render HTML submitted through forms?

How do I render HTML submitted through forms?

I am building a text-editor in a Rails 4 app. I am using javascript to pass data from content-editable into my forms to be saved into the database. All good so far.

Along with the text that a user saves, HTML is included... so my saved content looks like this:

<header class="header" contenteditable="true">
        This is a title
      </header>

<article class="content" contenteditable="true">This is the body<br></article>

When I display the content on the #index or in #edit the HTML is posted as normal text.

How do I get it to render?

Upvotes: 0

Views: 106

Answers (1)

pdobb
pdobb

Reputation: 18037

The reason you're seeing the HTML tags, etc, when displaying on your page is because Rails, by default, protects you from malicious data and escapes HTML tags. You can get around this by making sure the text is "safe" fist. The way that @bjhaid suggested in the comments (Simply using raw() is bad for user-supplied content because it essentially just trusts the content -- which could be anything, including a script tag that steels data from your users or gains access to your server.

The best way to sanitize user-supplied content is:

<%= sanitize(the_user_supplied_content) %>

The sanitize helper will remove dangerous tags and attributes and then mark the string as safe so that the rest of the content can go through unescaped.

UPDATE

To add an attribute so that it will not be removed by the sanitize helper:

# config/application.rb
config.action_view.sanitized_allowed_attributes = "my_new_attribute"

See also the api docs for sanitized_allowed_attributes.

Upvotes: 2

Related Questions