This guide explains how to integrate Highlight.js with Bootstrap dark/light mode in Django, while keeping Python and PowerShell code readable in both modes.
1. Include Highlight.js Theme
Always load a base theme (e.g., GitHub) in your <head> section:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.11.1/styles/github.min.css">
Optional: For full dark mode styling, use a dark-friendly theme such as atom-one-dark, dracula, or monokai.
2. Custom CSS Overrides
Move your custom Highlight.js overrides into static/css/main.css for maintainability. Ensure the CSS comes after the Highlight.js theme so overrides work properly.
3. Highlight.js Scripts
Load the core library and only the languages you need (Python and PowerShell) in your template:
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.11.1/highlight.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.11.1/languages/python.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.11.1/languages/powershell.min.js"></script>
<script>
hljs.highlightAll();
</script>
4. Usage in Templates
Wrap your code blocks with <pre><code> and add the language class:
<pre><code class="language-python">
def hello():
print("Hello World")
</code></pre>
<pre><code class="language-powershell">
Get-Process | Where-Object {$_.CPU -gt 100}
</code></pre>
5. Django Integration
- Place your custom CSS in
static/css/main.css. - Load it in your base template:
{% load static %} <link rel="stylesheet" href="{% static 'css/main.css' %}"> - Keep Highlight.js theme CSS in
<head>before your main.css overrides. - Collect static files for production:
python manage.py collectstatic
6. Tips & Notes
- Optionally, tweak `.hljs-keyword`, `.hljs-string`, and `.hljs-function` colors to mimic VSCode themes.
- Move inline CSS to
main.cssfor maintainability. - Works dynamically with Bootstrap 5 dark/light mode toggle.
- Only override hard-to-read colors in dark mode to preserve light mode colors.
This setup ensures your code blocks are readable in both dark and light modes while maintaining a clean and maintainable Django project structure.
Leave a Comment