【问题标题】:Sphinx documentation processor extension works differently for HTML and LaTeX output?Sphinx 文档处理器扩展对 HTML 和 LaTeX 输出的工作方式不同?
【发布时间】:2012-11-15 01:24:04
【问题描述】:

我有一个简单的狮身人面像扩展如下:

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: ?«(默认值)。我检查了node['foo'] 在分配TestDirective.run() 后的值是否正确,但在LaTeX 编写器运行之前,它似乎不会一直存在。

我做错了什么?

【问题讨论】:

    标签: python python-sphinx


    【解决方案1】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多