Python Markdown未添加codehili

2024-04-27 19:15:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我用Flask写博客,用Markdown的Python库为我生成HTML,我愿意有语法高亮显示,因此我使用markdown.markdown(string, extensions=['codehilite']

根据他们的wiki,应该添加一个html类

<div class="codehilite"><pre><code># Code goes here ...</code></pre></div>

但在我的翻译试用后,它似乎不起作用

^{pr2}$

我不知道这里有什么问题,我已经安装了Pygments,我已经升级了Markdown的lib,但是什么都没有。 这里的预期结果是Markdown将添加html类codehilite,这样我就可以让语法正常工作了。 这里有什么问题?在


Tags: divflaskstringhtmlwiki语法codeextensions
3条回答

我找到了另一个解决方案,markdown2

下面是几个例子(按照我的意愿…)

In [1]: import markdown2

In [2]: markdown2.markdown("> This is a paragraph and I am **bold**")
Out[2]: u'<blockquote>\n  <p>This is a paragraph and I am <strong>bold</strong></p>\n</blockquote>\n'

In [3]: code = """```python
if True:
    print "hi"
```"""
   ...: 

In [4]: markdown2.markdown(code, extras=['fenced-code-blocks'])
Out[4]: u'<div class="codehilite"><pre><code><span class="k">if</span> <span class="bp">True</span><span class="p">:</span>\n    <span class="k">print</span> <span class="s">&quot;hi&quot;</span>\n</code></pre></div>\n'

我已经确定,除了一般的喜怒无常外,可德希利特在它前面有一张单子时就会崩溃:

这种降价,以及它的变化,只是不起作用:

* apples
* oranges

    #!python
    import os

但是如果我在列表和代码之间加上一些东西,那它确实有效:

^{pr2}$

但这通常是不可预测的。我尝试了无数种组合,但成功率参差不齐。不高兴。。。在

使用fenced_code代替

然后我进入the other sub-extensions of pygments,尝试显式地添加fenced_代码扩展并重试fenced代码示例。效果更好。在

所以继续

pygmented_body = markdown.markdown(rendered_body, 
                                   extensions=['codehilite', 'fenced_code'])

我只使用fenced code获得了更大的成功:

* Don't need to indent 4 spaces
* Don't need something between the list and the code

~~~~{.python hl_lines='3'}
import os

print('hello, world')
~~~~

And final comments here.

很抱歉刚才看到你的问题。在

在python标记中,每行代码中需要4个空格。在

In [13]: text = """
   ....:        :::python
   ....:        import os
   ....:        """

In [14]: markdown.markdown(text, extensions = ['codehilite'])
Out[14]: u'<div class="codehilite"><pre><span class="kn">import</span> 
<span class="nn">os</span>\n</pre></div>'

相关问题 更多 >