Search code examples
javascriptreplacetinymcetinymce-4

How to replace variable in tinymce using template_replace_values?


I want to replace value using template_replace_values in tinymce. I have added <p>Name: {$username}, StaffID: {$staffid}</p> in textarea and template_replace_values:{username: "Jack Black",staffid: "991234"} in tinymce.init. When I run the code, the variable not replaced with value. It still showing the variable.

// Initialize TinyMCE
tinymce.init({
  selector: "textarea", // change this value according to your HTML
  plugins: "template",
  template_replace_values: 
  {
    username: "Jack Black",
    staffid: "991234"
  }
});
<!doctype html>
<html class="no-js" lang="">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Preview TinyMCE variable plugin</title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://cdn.tinymce.com/4/tinymce.js"></script>
</head>
<body>
  <form method="post">
    <textarea rows="18">
		 <p>Name: {$username}, StaffID: {$staffid}</p>
	</textarea>
  </form>
</body>
</html>

I follow the example shown in documentation.Is the variable declaration {$staffid} with braces and dollar sign incorrect?


Solution

  • The template_replace_values option happens when you insert content into the editor via a template (using the template plugin). It does not perform any sort of global find/replace of values as the editor is first initialized.

    In your example above you have some "default" content in the textarea that will be loaded into the editor as it is initialized. As that content is not inserted via a template the setting you reference won't impact the content.

    I have created a fiddle that shows how the template plugin works:

    http://fiddle.tinymce.com/1khaab

    If you use the Insert menu and select Insert template... you will see that the HTML of the template is inserted and the replacement takes place.