javascriptpythoncssdjangopygments

Showing the line numbers in <pre> in Django project using Pygments


I'm using the Pygments package in my Django project. When I try to render the code snippet in my template, it renders the whole data as follows:

Template:
...
{% pygmentify %}
<pre class="{{snippet.lang}}">{{snippet.body}}</pre>
{% endpygmentify %}
...

Final rendered HTML:

<pre lang="python">
...
<span class="kn">import</span> <span class="nn">hello</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">'hey'</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">test</span><span class="p">():</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">'in the function'</span><span class="p">)</span>
...
</pre>

It actually works with no pain. The entire code block is being highlighted properly. The thing is that I want to show the line number as well. Should I style them or there is only a simple Pygments configuration needed?

Thanks.


Solution

  • If you are using django-pygmentify, you can pass keyword arguments as indicated in their docs

    {% pygmentify linenos='inline' %}
    <pre class="{{snippet.lang}}">{{snippet.body}}</pre>
    {% endpygmentify %}