Search code examples
templatestinymcetinymce-4tinymce-plugins

TinMCE returning templates (assigned to variable or from API)


I'm working with TinyMCE, and trying to dynamically load templates through an API. However, even with a basic return, no templates load (such as setting the template list to a variable). They do load from an external JSON file (hardcoded). My question is then: how do I return or render custom TinyMCE templates?

For example:

This has hard-coded templates, so it works:

 templates: "/Content/data/templates.json"

But I am trying to achieve (on the basic level):

templates:
 function () {
   var test = 
        { title: 'Test template 1', content: 'Test 1' };

       return tinymce.util.JSON.parse(test); // doesn't work
      //return JSON.stringify(templates); // doesn't work
    },

On the original scale (code is incomplete):

templates: 
    function () {
            $.getJSON('/Template', function (result) {
              var data = {};
              $.each(result.ResponseObject, function (index, value) {
                data.title = value.Name;
                data.description = value.Name;
                data.content = value.Description;
                 // can't figure out how to return variable 
              });

            });

Solution

  • The templates option is expecting either an Array of templates or a URL (as a String) - you are sending it a function so that won't work.

    https://www.tinymce.com/docs/plugins/template/#templates

    Per the documentation...

    "If this option is a string then it will be requested as a URL that should produce a JSON output in the same format the option accepts."

    ...so I would update your server side code to return what the editor expects and just pass that URL in the TinyMCE configuration.