At some point every web developer will reach a point where he or she will be looking to create forms that support rich text editing. Allowing the user to format input can provide a great enhancement and in some cases, like a blog or robust forum, text formatting is kind of expected. There are many solutions out there and I’ve looked through a few them. I love open source projects that allow me to contribute and see what’s going on under the hood. The best open source projects show lots of activity and have very supportive communities. Quill was just what I was looking for.

I love the modularity of Quill. It can be simple.

See the Pen Quill Playground by Quill (@quill) on CodePen.

Or it can be robust!

See the Pen Autosave by Kevin McCormack (@HarlemSquirrel) on CodePen.

Getting started

  1. Include the style sheet
  2. Create the editor content
  3. Include the Quill library
  4. Initiate Quill editor
<!-- Include stylesheet -->
<link href="https://cdn.quilljs.com/1.1.6/quill.snow.css" rel="stylesheet">

<!-- Create the editor container -->
<div id="editor">
  <p>Hello World!</p>
  <p>Some initial <strong>bold</strong> text</p>
  <p><br></p>
</div>

<!-- Include the Quill library -->
<script src="https://cdn.quilljs.com/1.1.6/quill.js"></script>

<!-- Initialize Quill editor -->
<script>
  var quill = new Quill('#editor', {
    theme: 'snow'
  });
</script>

Using with rails

To grab the new formatted content you’ll need to use a little JavaScript. If you’re using a rails form helper, the easiest way to do this is to assign a unique id to a hidden input field in a form. Then, when the form is submitted, we will place the content from the Quill editor into this field and submit our form.

<!-- Form built with Rails form_for helper -->
<%= form_for :post, remote: true, html: { id: 'some-form' } do |f| %>
  <div class="form-group">
    <%= f.hidden_field :content, required: true %>
    <div id="editor-container" hidden="true"></div>
    <div id="editor"></div>
    <%= f.submit %>
  </div>
<% end %>
// JavaScript to fill in post content on from submission
var form = document.querySelector('#some-form');
var quill = new Quill('#editor', {
  theme: 'snow'
});

form.onsubmit = function() {
  var postContentInput = document.querySelector('#post-content');
  postContentInput.value = quill.root.innerHTML;
};

Then to display the new formatted content we can use sanitize from rails. We should whitelist the same tags that we have in our editor toolbar.

raw sanitize @post.body, tags: %w(strong em a), attributes: %w(href)