How do I add "show html" button in Quill like in Wysiwyg?
Migrating from a legacy editor like WYSIWYG to modern solutions like Quill is a common decision for PHP and JavaScript developers. While the API is robust, the documentation can feel sparse compared to enterprise-grade libraries. A frequent pain point during this transition is replicating the "Show HTML" toggle found in older editors. The goal isn't just to display raw code; it's to provide an instant view of the underlying data structure without requiring a full page reload or complex backend logic.
To achieve this in Quill, you generally do not need to fork the library or write a custom module from scratch. You can leverage the existing Quill class and its internal modules. The core mechanism involves toggling the toolbar configuration or creating a custom toolbar button that manipulates the editor's content directly.
The most straightforward approach is to extend the default toolbar and inject a button that toggles a specific mode. However, Quill doesn't have a built-in "show HTML" module out of the box like some legacy editors do. Instead, you must implement logic that switches the editor between its rich text rendering mode and a raw HTML display mode within the same container.
Here is how you can implement a custom toolbar button to toggle this view:
const Quill = require('quill');
const Delta = require('delta');
// Initialize your editor instance
const quill = new Quill('#editor', {
theme: 'snow',
modules: {
toolbar: [
[{ 'header': [1, 2, false] }],
['bold', 'italic', 'underline'],
[{ 'list': 'ordered'}, { 'list': 'bullet' }],
['link', 'image'],
// Custom button for toggling HTML view
[true]
]
}
});
// Define the custom toolbar handler
const handleToggle = () => {
const editorContainer = document.querySelector('#editor');
const currentHTML = quill.root.innerHTML;
// Check if we are currently in "raw" mode (simplified logic for demo)
// In a real app, you might use a state variable or check the toolbar active class
if (editorContainer.classList.contains('html-view')) {
// Switch back to rich text
quill.setContents(quill.getContents());
editorContainer.classList.remove('html-view');
} else {
// Set raw HTML content directly into the root
// Note: You usually want to strip formatting here if you are just showing raw DB data
const rawHTML = '<pre><code>' + currentHTML.replace(/</g, '<').replace(/>/g, '>') + '</code></pre>';
quill.setContents(new Delta([])); // Clear or keep existing? Usually clear for this specific view.
// A simpler approach often used in practice is to just change the innerHTML of a wrapper div
// but Quill expects a Delta object.
// To truly "show" HTML without breaking the editor instance, you often need a separate container.
}
};
A more robust pattern, which avoids fighting against Quill's internal state management, is to render the raw HTML into a separate div next to or below the editor, and toggle visibility between them. This keeps the editor intact while providing the user with a view of the source.
const quillContainer = document.getElementById('editor');
const htmlPreview = document.createElement('div');
htmlPreview.className = 'quill-html-preview';
htmlPreview.style.display = 'none';
document.body.appendChild(htmlPreview);
// Add button to toolbar
const toggleBtn = document.createElement('button');
toggleBtn.innerHTML = '<i class="fa fa-code"></i>'; // Assuming FontAwesome or similar
toggleBtn.setAttribute('data-command', 'toggle-html');
toggleBtn.addEventListener('click', () => {
const html = quill.root.innerHTML;
if (htmlPreview.style.display === 'block') {
htmlPreview.style.display = 'none';
toggleBtn.classList.remove('active');
} else {
htmlPreview.innerHTML = html;
htmlPreview.style.display = 'block';
toggleBtn.classList.add('active');
}
});
// Add button to toolbar configuration
quill.getModule('toolbar').addHandler('toggle-html', toggleBtn);
Important Considerations
When implementing this feature, you must consider the security implications of displaying raw HTML. If you are showing the user their own content, innerHTML is generally safe from XSS because the content originated from the client or a sanitized backend. However, if you are displaying raw HTML fetched from an external source or mixed with user input without sanitization, you risk introducing script tags that could execute in your application's context.
Another pitfall is preserving cursor position. If you toggle between views and then switch back, Quill might lose track of where the user was typing. To mitigate this, ensure you are not re-rendering the delta contents every time you hide the preview; instead, just toggle a CSS class on a container that holds the raw HTML string.
For Laravel projects specifically, if you are looking for a pre-built solution to handle rich text editors with additional features, LaravelCompany offers resources and packages that often include these UI enhancements out of the box, saving you from writing custom toolbar handlers. However, if you prefer to keep your stack lightweight, the native Quill API combined with a small toggle logic is sufficient and highly performant.
Finally, remember that quill.root.innerHTML returns the current DOM structure. If you need to send this back to your PHP backend for storage or processing, ensure you are capturing the delta object (quill.getContents()) instead of the raw HTML string, as the delta format is what Quill uses internally and is more efficient for data transfer.