I’m using the Toast UI library and I can have more than one editor per page. The editor displays and works, but when I try to get the HTML tags inside it to save them in my database, I always get errors with the functions. I tried: getHtml()
, getContent()
, and also getInstance()
.
The documentation and other resources I found while searching to solve my errors did not help me, or they were outdated.
This is my editor declaration code
<div class="textarea-editor" data-name="{{ fieldname }}" data-editorid="editor{{ field.unique_id }}" id="editor-{{field.unique_id}}"></div>
<!-- Inclusione dello script di Toast UI Editor -->
<script>
const Editor{{ field.unique_id }} = toastui.Editor;
const editor{{ field.unique_id }} = new Editor{{ field.unique_id }} ({
el: document.querySelector('#editor-{{ field.unique_id }}'),
height: '200px',
initialEditType: 'wysiwyg',
previewStyle: 'vertical',
toolbarItems: [
['heading', 'bold', 'italic', 'strike'],
['hr', 'quote'],
['ul', 'ol', 'task', 'indent', 'outdent'],
['table', 'image', 'link'],
['code', 'codeblock'],
['scrollSync'],
],
initialValue: `{{ field.value|safe }}`,
});
</script>
And here is what i tried without any result
$('.textarea-editor').each(function () {
var Uieditor = $(this).attr('data-editorid');
Uieditor = Uieditor.toastui.getInstance();
})
To correctly initialize and retrieve HTML content from multiple Toast UI Editor instances on a page, ensure each editor is correctly referenced and accessed. Here’s how you can adjust your setup:
- Store each editor instance in a global object:
window.editors = window.editors || {};
const uniqueId = '{{ field.unique_id }}';
window.editors[uniqueId] = new toastui.Editor({
el: document.querySelector('#editor-' + uniqueId),
height: '200px',
initialEditType: 'wysiwyg',
previewStyle: 'vertical',
toolbarItems: [
['heading', 'bold', 'italic', 'strike'],
['hr', 'quote'],
['ul', 'ol', 'task', 'indent', 'outdent'],
['table', 'image', 'link'],
['code', 'codeblock'],
['scrollSync'],
],
initialValue: `{{ field.value|safe }}`,
});
- Retrieve HTML content from all editors:
function getAllEditorContents() {
const contents = {};
for (const id in window.editors) {
if (window.editors.hasOwnProperty(id)) {
contents[id] = window.editors[id].getHtml();
}
}
return contents;
}
// Example usage
const allContents = getAllEditorContents();
console.log(allContents);
This streamlined setup correctly initializes each editor with a unique ID and allows for easy retrieval of the HTML content. Ensure each ID is unique to avoid conflicts and that the retrieval function is called appropriately within your application’s logic.