Search code examples
python-3.xdjangodjango-templatesdjango-template-filters

How to color code snippet in Django template


I am looking at coloring code on one of my Django page, the way PyCharm does it for instance.

def my_function(a):
    return a + 5


print(my_function(10))

displayed with colors such as (the background doesn't have to be black):

enter image description here

Is there an easy solution to capture anything within the <pre><code></code></pre> tags and applies this color code? Writing my own Django filter for this looks like an arduous task.


Solution

  • to highlight python, or any other language, code / syntax you need pygments

    pygments is used in sphinx, the defacto doc generator, to highlight syntax.

    i would like to point you to this sub-project of django: djangosnippets.org, the repo is already available on github (here), it's a kind of site that hosts snippets for django using pygments to highlight syntaxes, the point here is to have a look at the code and get inspired.

    refer to the doc https://pygments.org/docs/styles/ to learn more about howto write your own style or even more your own lexer.