Search code examples
htmlcsstinymcetinymce-4tinymce-5

Adding custom html and css in TinyMCE


I'm using TinyMCE and I would like to add custom html/css to the output. All the bullet lists created in the Tiny editor should have these css classes and an <i> tag like this:

<ul class="iconlist">
    <li><i class="icon-double-angle-right"></i> Item 1</li>
    <li><i class="icon-double-angle-right"></i> Item 2</li>
</ul>

Is there any way I can make Tiny output this exact html for all bullet lists?


Solution

  • EDITED: I have amended this answer to respond to comments from OP

    You can apply custom CSS to editor content using either the content_css or content_style configuration options:

    https://www.tiny.cloud/docs/configure/content-appearance/#content_css

    https://www.tiny.cloud/docs/configure/content-appearance/#content_style

    Many Tiny implementers use this to apply the same CSS to in-editor content as will be applied to that content when it is later rendered elsewhere, outside of the editor.

    However, to make the icons appear as expected within the editor, you will also need to configure the editor to allow for empty <i> elements. Empty <i> elements are by default removed from the editor. You can change this behavior by using the extended_valid_elements: configuration option:

    https://www.tiny.cloud/docs/configure/content-filtering/#extended_valid_elements

    extended_valid_elements: 'i[*]',
    

    All of this will allow external icon libraries that utilize <i> elements to function in TinyMCE (short of the specific setup each individual library may require).

    Edited to Add:

    how do I even configure Tiny so that it always adds the <i> element after an <li> element?

    One approach is to use a node filter on TinyMCE's serializer to add <i> elements as the first child of <li> elements. Here is a Tiny Fiddle example (using Font Awesome icons):

    https://fiddle.tiny.cloud/R4haab

    Documentation:

    https://www.tiny.cloud/docs/api/tinymce.dom/tinymce.dom.serializer/#addnodefilter

    The serializer is used when taking the content inside the editor (i.e. DOM nodes) and then converting that back to a string based HTML representation. So it's run on calls such as getContent(). This means that the <i> element is not added in realtime, as list elements are inserted, but will be added to any/all <li> elements (that don't already have it) whenever the serializer is run, including when saves are triggered, or when the form containing TinyMCE is POSTed.