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:

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

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:

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

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.

<br />
 toolbar:<br />
 - style-h1 style-h2 | bold italic | link<br />
 plugins:<br />
 - link<br />
 - stylebuttons<br />
 menubar: false<br />
 statusbar: false<br />
 relative_urls : false<br />

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.