gpt4 book ai didi

python - Sphinx 文档处理器扩展对 HTML 和 LaTeX 输出的工作方式不同?

转载 作者:太空狗 更新时间:2023-10-29 21:08:55 24 4
gpt4 key购买 nike

我有一个简单的 Sphinx 扩展如下:

from docutils import nodes
from docutils.parsers.rst import directives
from sphinx.util.compat import Directive

class testnode(nodes.Element):
def __init__(self, *args, **kwargs):
super(testnode, self).__init__(*args, **kwargs)
self['foo'] = '?'

def visit_testnode_latex(self, node):
self.body.append('Test: %s' % node['foo'])

def depart_testnode_latex(self, node):
pass

def visit_testnode_html(self, node):
self.body.append('<p>Test: %s</p>' % node['foo'])

def depart_testnode_html(self, node):
pass

class TestDirective(Directive):
has_content = False
required_arguments = 0
optional_arguments = 0
final_argument_whitespace = False
option_spec = {
'foo': directives.unchanged,
}

def run(self):
node = testnode()
node['foo'] = self.options.get('foo')
return [node]

def setup(app):
app.add_directive("testdirective", TestDirective)
app.add_node(testnode,
html=(visit_testnode_html,
depart_testnode_html),
latex=(visit_testnode_latex,
depart_testnode_latex))

给定一个文档包含

.. testdirective::
:foo: bar

HTML 输出包含 »Test: bar« 但 LaTeX 输出包含 »Test: ?«(默认值)。在 TestDirective.run() 中分配后,我检查了 node['foo'] 是否具有正确的值,但在 LaTeX 编写器运行之前,它似乎不会一直存在.

我做错了什么?

最佳答案

在逐步完成 Sphinx 的 LaTeX 编写器之后,我发现了这里的问题。这是您在 testnode 初始化程序中为 'foo' 关键字设置默认值的方式。

在 LaTeX 编写器中有一个要点,它对整个文档树进行深层复制,以便将其内联到另一棵树中。 Element 节点上的深度复制会初始化同一类的新节点,并通过构造函数传递原始节点的所有属性和内容。因此,当您的 testnode 被复制时,您的构造函数会覆盖传递给构造函数的原始“foo”属性。而是这样写,它应该可以工作:

class testnode(nodes.Element):
def __init__(self, *args, **kwargs):
super(testnode, self).__init__(*args, **kwargs)
if 'foo' not in self:
self['foo'] = '?'

这将防止您的默认值覆盖已传递给构造函数的属性的任何显式值。还有其他几种可能的变体。

关于python - Sphinx 文档处理器扩展对 HTML 和 LaTeX 输出的工作方式不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13390226/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com