0

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 
              });

            });
Hybride
  • 322
  • 4
  • 17

1 Answers1

1

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.

Michael Fromin
  • 13,131
  • 2
  • 20
  • 31
  • I tried the URL directly, and seems you are correct - I would have to change the code on that part. But is it not possible to return an array with an Ajax function to populate the templates? – Hybride May 02 '17 at 15:28
  • (Ran out of time) Edit: for example, the API has a field called "Name" instead of "title". I wanted to assign the "Name" to "title" and return that so it could populate the Templates. – Hybride May 02 '17 at 15:36
  • You can always use a variable in the TinyMCE configuration and just make sure that variable has the proper content when you need it - yes. I would still make sure that the data exists before you try to init TinyMCE as its not expecting that data to arrive post initialization. – Michael Fromin May 02 '17 at 16:13