Django 2025-04-12

How to highlight code in Django templates with EnlighterJS

With TinyMCE you can have total control over your rich text editing. In Django instead of using the standard type of the field in the model (like for example models.TextField()), we can use django-tinymce package to beautify the text of our posts:

from django.db import models
from tinymce.models import HTMLField

class MyModel(models.Model):
    ...
    content = HTMLField('Content')

In our settings file, we should create the configuration for TinyMCE (the example below):

# TinyMCE
TINYMCE_DEFAULT_CONFIG = {
    'cleanup_on_startup': True,
    'custom_undo_redo_levels': 20,
    'height': 500,
    'selector': 'textarea',
    'theme': 'silver',
    'plugins': '''
            textcolor save link image media preview codesample contextmenu
            table code lists fullscreen  insertdatetime  nonbreaking
            contextmenu directionality searchreplace wordcount visualblocks
            visualchars code fullscreen autolink lists  charmap print  hr
            anchor pagebreak
            ''',
    'toolbar1': '''
            fullscreen preview bold italic underline | fontselect,
            fontsizeselect  | forecolor backcolor | alignleft alignright |
            aligncenter alignjustify | indent outdent | bullist numlist table |
            | link image media | codesample |
            ''',
    'toolbar2': '''
            visualblocks visualchars |
            charmap hr pagebreak nonbreaking anchor |  code |
            ''',
    'contextmenu': 'formats | link image',
    'menubar': True,
    'statusbar': True,
    'invalid_elements': 'code'
}

Don't forget to add a new URL in the urls.py file of the project:

path('tinymce/', include('tinymce.urls')),

Why use EnlighterJS?

EnlighterJS is a free, open-source, full-featured syntax highlighter for the web. It's written in pure JavaScript and doesn't require any other libraries like jQuery. It's highly customizable and supports many languages and themes.

To highlight our syntax with EnlighterJS we should download CSS and JS files (from its page) to the static folder and then use them in the template.

Code for the CSS:

<link rel="stylesheet" href="/static/css/enlighterjs.min.css" />

And code for the JS:

<script type="text/javascript" src="/static/js/enlighterjs.min.js"></script>
<script type="text/javascript">
        // INIT CODE - simple page-wide initialization based on css selectors
        // - highlight all pre + code tags (CSS3 selectors)
        // - use Python as default language
        // - use theme "dracula" as default theme
        // - replace tabs with 4 spaces
        EnlighterJS.init('pre', 'code', {
                language : 'python',
                theme: 'dracula',
                indent : 4,
                });

        // Example of increasing the font size of selected elements
        let snippets = document.getElementsByClassName('enlighter');
        for (let s=0; s < snippets.length; s++) {
            snippets[s].style.fontSize = '130%';
        }
</script>

More examples are here.

Manual Highlighting

If your syntax isn't highlighted, you can manually (by clicking 'Source code' in the TinyMCE toolbar) try to add a given attribute as follows:

<pre data-enlighter-language="python"></pre>

After the aforementioned operations, your highlighted code on the page should look as beautiful as mine :)

Conclusion

Combining the power of TinyMCE for content creation and EnlighterJS for syntax highlighting gives you a professional-grade blogging platform. Your technical articles will be much easier to read, especially when explaining complex workflows like asynchronous tasks with Celery.


Scientific Dev
Scientific Dev
Educator & Developer