使用Python Markdown库在标题上生成永久链接

8 投票
3 回答
1830 浏览
提问于 2025-04-16 15:34

我在想怎么用Python的Markdown库从下面的标记生成永久链接:

A header
========

A paragraph

我想要的输出结果大概是这样的:

<span id="a-header"></span>
<h1>
  A header
  <a class="headerlink" title="Permalink to this headline" href="#a-header">¶</a>
</h1>
<p>A paragraph</p>

回答:

感谢@BlaXpirit(查看答案

使用headerid这个Python Markdown扩展,然后输入以下内容:

# A header [¶](#a-header) {#a-header}

A paragraph

这样就会生成以下输出:

<h1 id="a-header">
  A header
  <a href="#a-header">¶</a>
</h1>

接着用一些CSS样式来得到常见的输出效果,像这样:

h1 a{visibility:hidden;}
h1:hover a{visibility:visible;}

3 个回答

0

Pandoc会给每个标题分配一个独特的标识符,这个标识符是根据你想象的规则生成的:就是把标题变成小写字母,空格用连字符替代。这个标识符可以用来生成HTML、LaTeX和其他格式的可选目录。在HTML中,它会自动生成可以链接的标识符,特别适合用来做内部引用;Markdown的语法是:

 See the section on [header identifiers](#header-identifiers-in-html).

正如我们在用户指南中看到的,详细信息可以在http://johnmacfarlane.net/pandoc/README.html#header-identifiers-in-html找到。

1

你可以使用Python-Markdown的目录扩展来生成永久链接。根据Python-Markdown的文档,如果可以的话,最好传递一个扩展的实例,而不是简单的字符串。

import markdown
from markdown.extensions.toc import TocExtension

markup = """
A header
========

A paragraph
"""

html = markdown.markdown(markup, extensions=[TocExtension(permalink=True)])
print(html)


configs = {'toc': {'permalink': True}}
html = markdown.markdown(markup, extensions=['toc'], extension_configs=configs)
print(html)

这是对另一个问题的回答,里面展示了如何通过将永久链接选项设置为一个字符串来更改段落符号。

1

在Python中使用Markdown有一个扩展功能可以实现这个效果。
它还允许你为标题指定一个你喜欢的id,像这样:

A header            {#a-header}
========

撰写回答