8 September 2015 · About 2 minutes read

Using TinyMCE Content CSS with Rails Asset Pipeline

Recently, whilst building a small CMS system using TinyMCE and the tinymce-rails gem, I needed to inject some custom CSS so that the editor’s styles matched those of the site.

TinyMCE lets you do this using the content_css option:

# app/assets/javascript/tinymce.coffee
tinymce.init {
  selector: ".tinymce",
  content_css: ["/assets/tinymce-content.css"],
  # ...
}

Unfortunately, whilst this is fine in development, where CSS and other assets are compiled on demand, when deploying to a server and running under production, the URL above becomes invalid, causing 404 errors and broken styles.

Linking to Precompiled Content CSS

To ensure the content CSS assets are compiled, we first need to add them to the precompiled assets list:

# config/initializers/assets.rb
Rails.application.config.assets.precompile += %w( tinymce-content.css )

Next, we need to ensure that the content_css option uses the compiled asset’s URL. We can do this by using a snippet of ERB in our coffeescript file:

# app/assets/javascript/tinymce.coffee.erb
tinymce.init {
  selector: ".tinymce",
  content_css: ["<%= asset_url 'tinymce-content.css' %>"],
  # ...
}

Note that you also need to add the .erb extension to the filename.

With that, the correct compiled URL for tinymce-content.css will be inserted into your tinymce.init call, and the styles will be loaded correctly into the editor.

Testing it out in development

You can check the correct styles are loaded in development when precompiled by running:

$ bin/rake assets:precompile

Then restart your server and load the page with your editor.

Don’t forget to remove the precompiled assets with:

$ bin/rake assets:clobber
Chris Blunt
Chris Blunt @cblunt
Chris is the founder of Plymouth Software. As well as code and business, he enjoys being a Dad, swimming, and the fine art of drinking tea.