preator
preator

Reputation: 91

Rails - close html tags when you enter html in a form

Is there any way to close html tags if a user forgets to? E.g. when the user input is:

<b>small</b><i>test

Is there a way in Rails to automatically add the closing </i> tag, so that all the following html won't be italic?

I used .html_safe to interpret everything as html, but I would like to terminate <i> too.

Upvotes: 2

Views: 541

Answers (3)

Roland Mai
Roland Mai

Reputation: 31077

Rails doesn't have any built in capability to do this however you have a couple of options:

  1. Nokogiri - easy to install on pretty much all platforms (gem install nokogiri)
  2. Tidy - The second post has the details to use it in linux and windows

Using nokogori you can simply do:

html = "<b>small</b><i>test"
clean = Nokogiri::HTML::DocumentFragment.parse(html).to_html
# clean = "<b>small</b><i>test</i>"

Upvotes: 4

x10
x10

Reputation: 3834

A decent way to do this would be to feed the input to a dom parser and then have that parser output correct HTML.

Note that this isn't fool proof and if the user makes too many mistakes, the parser won't know what to do.

I'd suggest Nokogiri

Upvotes: 0

shingara
shingara

Reputation: 46914

Rails can't do that to you.

You can use some template system like Haml or Slim to don't forget that.

You can do it by your own editor too.

Upvotes: 0

Related Questions