我想使用自定义图像指令“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>
这是我的 autoimage 实现,它是内部 Image 指令的子类:
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)