我正在创建一个自定义指令来显示 pydata-sphinx 主题中所有可用组件的列表。我尽量避免使用原始指令,因此我正在构建一个自定义指令以保持与其他构建器的兼容性。
这是代码的重要部分:
"""A directive to generate the list of all the built-in components.
Read the content of the component folder and generate a list of all the components.
This list will display some information about the component and a link to the
GitHub file.
"""
from docutils import nodes
from sphinx.application import Sphinx
from sphinx.util.docutils import SphinxDirective
class ComponentListDirective(SphinxDirective):
"""A directive to generate the list of all the built-in components."""
# ...
def run(self) -> List[nodes.Node]:
"""Create the list."""
# ...
# `component` is a list of pathlib Path
# `url` is a list of string
# `docs` is a list of string
# build the list of all the components
items = []
for component, url, doc in zip(components, urls, docs):
items.append(nodes.list_item(
"",
nodes.reference("", component.name, refuri=url), #this line is the source of the issue
nodes.Text(f": {doc}")
))
return [nodes.bullet_list("", *items)]
当我尝试在 sphinx 构建中执行前面的代码时,出现以下错误:
Exception occurred:
File "/home/borntobealive/libs/pydata-sphinx-theme/.nox/docs/lib/python3.10/site-packages/sphinx/writers/html5.py", line 225, in visit_reference
assert len(node) == 1 and isinstance(node[0], nodes.image)
AssertionError
如果父节点不是 TextELement ,此断言由 sphinx 执行。所以我尝试将东西包装在 Text
节点中:
nodes.Text(nodes.reference("", component.name, refuri=url))
但是我只得到参考的__repr__
,而不是真正的链接(我认为这是因为文本节点只接受字符串)所以我也尝试使用
TextElement
:
nodes.TextElement("", "", nodes.reference("", component.name, refuri=url))
这也引发了一个错误:
Exception occurred:
File "/home/borntobealive/libs/pydata-sphinx-theme/.nox/docs/lib/python3.10/site-packages/docutils/nodes.py", line 2040, in unknown_departure
raise NotImplementedError(
NotImplementedError: <class 'types.BootstrapHTML5Translator'> departing unknown node type: TextElement
有人知道我应该如何在项目符号列表的开头添加链接吗?
如果您错过了一些上下文,您可以在这里找到指令的完整代码
items.append(nodes.list_item(
"",
nodes.paragraph(
"",
"",
nodes.reference("", component.name, refuri=url),
nodes.Text(f": {doc}")
)
)