How to add custom menu opton in Tinymce in Rails

319 views Asked by At

I am using tinymce-rails gem for Tinymce and I want to add custom menu option. Right now I am doing what is suggested in the readme of gem like:

<%= f.input :content , :label => false ,  :placeholder => 'Content', input_html: {class: "tinymce"} %>
<%= tinymce %>

I am using simple-form.

I want to add a drop-down in the editor with a bunch of options (I have an array of names) and when user clicks on an option then the selected name should be inserted in the view of editor. And those names will be dynamic.

I tried to pass many options to the initialiser tinymce but unable to get the result.

1

There are 1 answers

2
Allan W Smith On

Rather than using the default initiator from the gem you could initiate tinymce manually and create the menu item at the same time:

http://www.tinymce.com/tryit/menuitem.php

Something like this:

<script type="text/javascript">
    tinymce.init({
        selector: '.my-class textarea',
        toolbar: "styleselect | bold italic | mybutton",
        setup: function(editor) {
        <% @my_items.each_with_index do |name, index| %>
            editor.addMenuItem('<%= name %>', {
                text: '<%= name %>',
                context: 'tools',
                onclick: function() {
                    editor.insertContent('<%= name %>');
                }
            <%= index == (@my_items.count - 1) ? '});' : '}),' %>
        < % end %>   
    });
</script>

We use a ternary operator to choose the correct closing tag based on the index of the names.

Theoretically you can also do this in the config/tinymce.yml file, but due to the dynamic nature it's not really plausible.

Something else you may want to look into is passing the menu to the activeEditor like:

tinyMCE.activeEditor.controlManager.get('my_menu')