Tony_KiloPapaMikeGolf
Tony_KiloPapaMikeGolf

Reputation: 889

Select TinyMCE template: set content instead of append to the current content

Context: C# .NET Web application.

TinyMCE text editor. When selecting a template, the text is appended to the content of the textarea.

For this specific textarea, the productowner requires the content to be set to the text of the selected template, not appended to the already set content. So the current content needs to be cleared first, when the template is selected.

Can anybody please tell me, how this can be achieved?

Not that it is relevant, but here is a snippet of my code and a screenshot:

<script type="text/javascript">
var e = tinyMCE.get("MailText");
if (!e) {
    tinymce.init({
    height: 200,
    selector: "textarea#MailText",
    theme: "modern",
    plugins: ["template","code"],
    templates: [ @Html.Raw(finalizeQueryVm.Templates)],
        statusbar: false,
        resize: false,
        toolbar1: "insertfile undo redo | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist | code",
});
}

enter image description here

Upvotes: 1

Views: 1770

Answers (1)

Michael Fromin
Michael Fromin

Reputation: 13744

The template plugin has no flag or setting to dictate when to replace or insert content. There are a couple of things you could do...

1 - Modify the template plugin

The code for the template plugin could certainly be modified to insert or set content based on whatever criteria you have for each template. The plus here is you have complete control over the code. The minus is that you have to maintain these changes each time you update TinyMCE to ensure the template plugin still functions as you expect.

2 - Rely on TinyMCE Editor Events (e.g. BeforeSetContent)

When things happen in the editor it fires events to notify you - this allows you to take action based on the event. One of these events is BeforeSetContent. You could put some marker in templates to flag that this is a "template" being inserted and then trigger a removal of the editor's current content before the insertion. For example...

tinymce.init({
  selector: "#myEditor",
  ...
  setup: function (editor) {
    editor.on('BeforeSetContent', function(e) {
      console.log('BeforeSetContent: ' + e.content);
      if (e.content.startsWith("<!-- replace -->")) {
        console.log('REMOVING EXISTING CONTENT');
        editor.setContent("");
      }
    });
  }
})  

This example assumes that the first part of the template is the HTML comment <!-- remove -->. There is no way to know what triggers the setting of content - it could be anything from pasting to inserting a template so you will need to have something in the template to allow you to know that you want to remove the editor's current content.

Upvotes: 2

Related Questions