tinymce in rails

Recently I had to find a way to add heading1 and heading2 buttons directly to the TinyMCE toolbar. Now considering that I had to do it in rails made it somewhat difficult. Anyhow I found one easy way doing it and here I am going to explain it to you guys. Hopefully someone will find this helpful.

My Setup

I am using

  • Rails
  • tinymce-rails plugin – link

So the easiest way to do this as far as I know is by using TinyMCE plugins. So first of all we will see how we are going to add a plugin to tinymce on our rails installation.

How to


1. First of all create a couple of directories in the structure given below on your assets path:

  • Place to create the directories: app/assets/javascripts/
  • First directory to  create: tinymce
  • 2nd one: plugins/
  • 3rd one: stylebuttons (This is the plugin name)

2. Now under the directory with the plugin name create a file called: plugin.js

3. Once you do this add the code below to it:

tinyMCE.PluginManager.add('stylebuttons', function(editor, url) {
  ['h1', 'h2'].forEach(function(name){
   editor.addButton("style-" + name, {
       tooltip: "Toggle " + name,
         text: name.toUpperCase(),
         onClick: function() { editor.execCommand('mceToggleFormat', false, name); },
         onPostRender: function() {
             var self = this, setup = function() {
                 editor.formatter.formatChanged(name, function(state) {
             editor.formatter ? setup() : editor.on('init', setup);

4. Once you have done that, save it and lets add this file to the precompile assets configuration file in rails.

For that open the file called asstes.rb.

Full path: config/initializers/assets.rb

Add this line to the end of this file:

Rails.application.config.assets.precompile += %w( tinymce/plugins/stylebuttons/plugin.js )

5. Now the next step is to add the button names and plugin names in the tinymce.yml file

So open the file at: config/tinymce.yml

And add the plugin name and buttons you need like below.

 - style-h1 style-h2 | bold italic | link
 - link
 - stylebuttons
 menubar: false
 statusbar: false
 relative_urls : false

So that’s it. Once you restart your rails server, you will have the toolbar with both the heading buttons. I hope you found this helpful. If you need nay help or any doubts, please comment below and I will look into it.