CkEditor - Template loaded from AJAX

荒凉一梦 提交于 2019-12-05 18:07:08

You can't follow this way. The first reason is that editor expects html to be a string, not a function. The second reason is that your AJAX request doesn't make sense since it's called asynchronously and return html is executed before the request is finished.

Anyway, what you want to do is to preload your temple(s) once the editor is ready. You can simply change the following XHR request with a jQuery code but you have to remember that you should call CKEDITOR.addTemplates in success callback:

CKEDITOR.replace( 'editor1', {
    templates: 'my',
    on: {
        instanceReady: function( argument ) {
            var httpRequest = new XMLHttpRequest();

            httpRequest.onreadystatechange = function() {
                CKEDITOR.addTemplates( 'my', {
                    templates: [
                        {
                            title: 'My AJAX-driven template',
                            html: this.responseText
                        }
                    ]
                });
            };
            httpRequest.open( 'GET', 'yourFile.html' );
            httpRequest.send();
        }
    }
});

If you really wanted to do this live (hard way, I don't recommend it to you), you should overwrite templates command with your code which loads custom templates and then executes the real command. I don't think you need to do this though.

Have fun!

If you're okay with using the bad async: false attribute, I've solved this by changing my custom config file to this:

$.ajax({
    type: "POST",
    url: '/editor/getTemplates',
    async: false,
    dataType: "json",
    success: function(data) {


        CKEDITOR.addTemplates("default",{
        imagesPath:CKEDITOR.getUrl(CKEDITOR.plugins.getPath("templates")+
       "templates/images/"),
        templates:data});


    },
    error: function() {
        alert("Error!");
    }
});

Where the server loops through all templates and generates a json encoded array as templates should be.

If you don't set async to false (since it's depercated in newer jQuery), the problem will be that the editor will try to access the array before it arrived, In that case I think you'd have to edit internal files.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!