Skip to main content
 首页 » 编程设计

python之狮身人面像 : custom image directive surrounded by unwanted html link

2025年05月04日11lyj

我想使用自定义图像指令“Autoimage”,它允许在 Sphinx v1.0.8 中为不同的构建器提供不同的缩放选项。缩放有效,但由于我不知道的原因,html 输出被 <a href=...> 包围标签。示例:

.. image:: /img/foo.png 

结果

<img src="../_images/foo.png" alt="foo"></img> 

鉴于

.. autoimage:: /img/foo.png 

结果

<a class="reference internal" href="../_images/foo.png"> 
    <img style="width: 16.0px; height: 16.0px;" src="../_images/foo.png" alt="foo"></img> 
</a> 

这是我的自动图像实现,它是内部图像指令的子类:

import os 
from docutils import nodes 
from docutils.parsers.rst import directives 
from docutils.parsers.rst.directives.images import Image 
 
 
class Autoimage(Image): 
    option_spec = { 
            'scale-html': directives.percentage, 
            'scale-latex': directives.percentage, 
            'scale-epub2': directives.percentage, 
            'scale-mobi': directives.percentage, 
            'scale': directives.percentage, 
            } 
 
    def run(self): 
        env = self.state.document.settings.env 
        builder_name = env.app.builder.name 
 
        # treat all filenames as relative to the source dir (of the project) 
        if self.arguments[0].startswith('/') or self.arguments[0].startswith(os.sep): 
            relFileBase = self.arguments[0][1:] 
        else: 
            relFileBase = self.arguments[0] 
 
        extension = '' 
        defaultScale = 100 
        # when using LaTeX, look for pdf images first 
        if builder_name == 'latex': 
            defaultScale = 50 
            extension = '.pdf' 
        # use png images as the default/fallback 
        realPath = os.path.join(env.srcdir, relFileBase + extension) 
        if extension == '' or not os.path.exists(realPath): 
            extension = '.png' 
 
        realPath = os.path.join(env.srcdir, relFileBase + extension) 
        if not os.path.exists(realPath): 
            print('Could not find image %s' % realPath) 
            return False 
 
        self.arguments[0] = self.arguments[0] + extension 
 
        # this gets cached in the environment and is shared among builds, 
        # so for this to work use -E with sphinx-build :/ 
        self.options['scale'] = self.options.get('scale-' + builder_name, defaultScale) 
 
        return Image.run(self) 
 
 
def setup(app): 
    app.add_directive('autoimage', Autoimage) 

请您参考如下方法:

每当使用“比例”选项时,Sphinx 会自动添加指向原始版本的链接,即使比例为 100%。