Search code examples
javascriptjquerytinymcethymeleaf

How to load HTML file from server into Tinymce editor


I needed to be able to take a HTML file and load into an editable textarea in TinyMce. The documentation on the Tinymce website does not provide clear instructions on this.

I am placing my code in a Thymeleaf template in Spring MVC.


Solution

  • First, we need to load the file using ajax and jquery.

    <script>
    $(document).ready(function(){
        $("button.ext").click(function(){
            $.ajax({url: "hello", success: function(result){
                $("#div1").html(result);
            }});
        });
    });
    </script>
    

    This script requires a button with class ext. In the html body, need to make this button

    <button class="ext">Get External Content</button>
    

    In the header in ... we need to have the required tinymce script

    tinymce.init({
        selector: "textarea",
        plugins: [
            "advlist autolink lists link image charmap print preview anchor",
            "searchreplace visualblocks code fullscreen",
            "insertdatetime media table contextmenu paste"
        ],
        toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image"
    });
    

    So the selector is textarea as you see.

    In the html body, put this textarea.

    <textarea id="t1" style="width: 300px; height: 100px;"></textarea>
    

    Take note of the id="t1".

    Let's put a now that will set the content of the textarea

        <script type="text/javascript">
    function updateEditor(taClass) {
      var table = $("#div1").html();
      tinyMCE.get(taClass).setContent(table);
    }
    </script>
    

    So in the above script first there is a function with the ability to pass the parameter (taClass). In our case this will be t1 (for id="t1").

    Next we assign the variable table to the id #div1 that we set in the first ajax script.

    In this example we use a button that completes our job onClick.

    <button id="div1button" onclick="updateEditor('t1'); return false;">Set content to tinyMCE textarea 1</button>
    

    Please note that this is not 100% perfect or pretty. This is meant to be an educational example to illustrate the concepts of how this can be done. The content loaded by ajax will be apparent and it will be your job to hide it or do whatever you want - to make it pretty.

    For me this example shown works in Thymeleaf by the way.