Code Syntax Highlighting in django with Pygments

Syntax Highlighting is a very much useful if you put code on your website. This can be easily achived with django-pygments. over 300 languages are supported.

List of supported Languages: http://pygments.org/languages/

django-pygments is the implementation of the pygments syntax highlighter for django.
usage is quite simple. after setting up everything, you need to put necessary template tags and then place your code in pre tags with a lang attribute specifying the language of the source code in your template.

example: <pre lang=”python”>YOUR CODE</pre>

1. First, Install the following packages.

pip install pygments
pip install django-pygments

2. add django_pygments in installed apps in settings.py file.

INSTALLED_APPS = [
    . . . .
    . . . .
    ‘django_pygments’,
 
]

3. Enter this command in the terminal to generate the vs.css file

pygmentize -S vs -f html > vs.css

and place the generated vs.css file in static/css directory so that you can link it with template.

Here is an template example showing a Sample C source code highlighting.

{% load staticfiles%}
<!DOCTYPE html>
<html>
<head>
<title>django-pygments demo</title>
<link rel="stylesheet" type="text/css" href="{% static 'css/vs.css' %}">

</head>
<body>

<h2>django-pygments demo</h2>

{% load pygmentify %}
{% pygment %}

<pre lang="c">

#include<stdio.h>

int main()
{
printf("Hello World");
return 0;
}

</pre>
{% endpygment %}


</body>
</html>

Leave a Reply

Your email address will not be published.