简体   繁体   中英

How to Add "lang" Attribute to a <pre> Tag in python-markdown?

I'm using django-pygmentes in order to highlight my code-blocks. I'm writing the contents with markdown and convert it to HTML in the view part. Everything is ok. Now, I want to implement the highlighting side. The Pygmentes package needs something like this in order to apply the colors:

<pre lang="python">...</pre>

But, it's what I get when I write a code block in my post:

<pre><code clas="language-python">...</code></pre>

Here is my markdown:

```python
print('Hey')

So, Pygments could not find the element. Is there any way to override any method and apply the changes?

UPDATED: Now, I've installed the pygments and added this extension to the markdown extensions. Here is my markdown and what it generates:

```{lang="python"}
print('Hello World')

Output:

<pre><code lang="python">
print('Hello World')
</code></pre>

Which is great, but there is no highliting yet.. :( I also linked the classic styles.css file after running pygmentize -S default -f html -a .codehilite > styles.css and it linked properly.

Here is my custom markdown filter. The problem might be coming from this module:

from django import template
from django.template.defaultfilters import stringfilter

import markdown as md

register = template.Library()


@register.filter()
@stringfilter
def markdown(value):
    return md.markdown(value, extensions=['markdown.extensions.fenced_code', 'markdown.extensions.attr_list'])

You can always revert to raw HTML. Simply insert the HTML directly into your document:

<pre lang="python">...</pre>

You could enable the CodeHilite Markdown extension, which uses Pygments to highlight code blocks. Python-Markdown will take the language set on the fenced code block and pass it to pygments for you. No need to use a Django app.

So long as you are using Python-Markdown version 3.3+ and you have enabled the attr_list extension, you can assign arbitrary key/value pairs directly to fenced code blocks (be sure to include the curly braces).

``` { lang=python }

However, that will still assign the attribute to the code tag, not the pre tag. Like this:

<pre><code lang="python">...

Also, note that the default behavior of generating <pre><code clas="language-python"> is the recommended way to designate the language of a codeblock in the HTML spec (see the second “example” ). One might consider it a bug for a tool to not recognize that method of designating the language for a code block.

I forgot to add the highlit extension in the custom filter module. Now, everything is working well. Thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM