【问题标题】:Generate permalinks on header with python markdown library使用 python markdown 库在标题上生成永久链接
【发布时间】:2011-04-12 13:43:56
【问题描述】:

我想知道如何使用 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 (see answer)

使用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;}

【问题讨论】:

    标签: python markdown permalinks


    【解决方案1】:

    Python 中的 Markdown 有一个 extension 可以做到这一点。
    它还允许您为标题指定一个您喜欢的 id,如下所示:

    标头 {#a-header} ========

    【讨论】:

    • 这就是我一直在寻找的,但是用错误的关键字搜索!谢谢
    【解决方案2】:

    您可以为 Python-Markdown 生成带有 Table of Contents 扩展名的永久链接。 Python-Markdown documentation 指出,如果可能,最好传递扩展实例而不是字符串。

    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)
    

    An answer to a different question 展示了如何通过将永久链接选项设置为字符串来更改段落符号。

    【讨论】:

    • 谢谢,不过如果你不想要这些额外的 a 标签,你可以使用html = markdown.markdown(markup, extensions=[TocExtension(baselevel=1)])
    【解决方案3】:

    Pandoc 根据您想象的规则为每个标题关联一个唯一标识符:id 是小写标题,空格替换为连字符。这用于为 HTML 和 LaTeX 以及其他输出格式生成可选的目录。在 HTML 中,它会自动生成可链接的 id,特别是可用于内部交叉引用;降价语法是:

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

    正如我们在http://johnmacfarlane.net/pandoc/README.html#header-identifiers-in-html 的用户指南中所读到的那样

    【讨论】:

    • 谢谢,不知道 Pandoc,但我的问题是关于 python markdown 库
    • 我想知道是否是这种情况,但实际上从问题的内容中并不清楚。我在markdown提要上看到了,我没有关注python。
    • 你是对的,我没有明确提到 python markdown 库。我将更新问题。
    猜你喜欢
    • 1970-01-01
    • 2015-08-21
    • 1970-01-01
    • 2018-05-20
    • 2019-06-10
    • 1970-01-01
    • 2014-11-28
    • 1970-01-01
    • 2023-04-05
    相关资源
    最近更新 更多