Linux, OpenSource, Programming And Hacks

Aug 24, 2016

Code Syntax Highlighting in django with Pygments

Aug 24, 2016

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:

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 file.

    . . . .
    . . . .

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>
 <title>django-pygments demo</title>
 <link rel="stylesheet" type="text/css" href="{% static 'css/vs.css' %}">

<h2>django-pygments demo</h2>

{% load pygmentify %}
{% pygment %}

<pre lang="c">


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

{% endpygment %}


No comments:

Post a Comment