Highlight source code

How to highlight source code with Tinymce rich text editor

by: AWS November 15,2022 last update: 4 months, 1 week Django WYSIWYG Tinymce

In the post i will try to explain how to highlight source code using Tinymce with Django web framework.

If you didn't install Tinymce text editor, please check my previous post, once you finish you can continue with this tutorial 

So as you might noticed when using Tinymce as it is you can only insert code but the language syntax won't be highlighted 

like the following example:

class PythonClass:

     def __init__(self):


Adding Prism to our templates

In order to highlight the source code we will be using Prism 
We need to add the following CSS and Javascript files to the pages that contains the sources code which needs to be highlighted

you can include those tags in your base.html template or specifically insert them only in pages that requires them 

include Prism in base.html template

  1. Insert the following in the head tag of your base.html templae
    <!-- Prism CSS-->
    <link rel="stylesheet" href="https://unpkg.com/dracula-prism/dist/css/dracula-prism.css">
  2. Insert the following script tags in the botton of your base.html template just before the body closure tag
        <!-- Prism -->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.17.1/prism.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.17.1/components/prism-python.min.js"></script>
  3. The last thing to do is to update the Tinymce rich text editor  config in your django setting.py file
        "height": "320px",
        "width": "960px",
        "menubar": "file edit view insert format tools table help",
        "plugins": "advlist autolink lists link image charmap print preview anchor searchreplace visualblocks code codesample "
        "fullscreen insertdatetime media table paste code help wordcount spellchecker",
        "toolbar": "undo redo | bold italic underline strikethrough | fontselect fontsizeselect formatselect | alignleft "
        "aligncenter alignright alignjustify | outdent indent |  numlist bullist checklist | forecolor "
        "backcolor casechange permanentpen formatpainter removeformat | pagebreak | charmap emoticons | "
        "fullscreen  preview save print | insertfile image media pageembed template link anchor codesample | "
        "a11ycheck ltr rtl | showcomments addcomment code codesample",
        "custom_undo_redo_levels": 30,
        "language": "en_EN",  # To force a specific language instead of the Django current language.


We added the codesample to plugins and toolbar which will add a new menu in Tinymce as you can see in the following screen

Tinymce Code sample