Mar*_*ech 18 python documentation restructuredtext substitution python-sphinx
我正在使用Sphinx来记录将部署在不同服务器中的Web服务.该文档中包含用户单击的URL示例,它们应该可以正常工作.我的问题是主机,端口和部署根目录会有所不同,必须为每个部署重新生成文档.
我尝试定义这样的替换:
|base_url|/path
.. |base_url| replace:: http://localhost:8080
Run Code Online (Sandbox Code Playgroud)
但生成的HTML不是我想要的(在生成的链接中不包括"/ path"):
<a href="http://localhost:8080">http://localhost:8080</a>/path
Run Code Online (Sandbox Code Playgroud)
有人知道如何解决这个问题吗?
小智 23
Sphinx v1.0中的新功能:
sphinx.ext.extlinks - 缩短外部链接的标记
http://sphinx.pocoo.org/ext/extlinks.html
该扩展添加了一个新的配置值:
extlinks
此配置值必须是外部站点的字典,将唯一的短别名映射到基本URL和前缀.例如,要为上述问题创建别名,您可以添加
extlinks = {'issue':
('http://bitbucket.org/birkenfeld/sphinx/issue/%s', 'issue ')}
Run Code Online (Sandbox Code Playgroud)
现在,您可以将别名用作新角色,例如:issue:`123`.然后插入链接到http://bitbucket.org/birkenfeld/sphinx/issue/123.如您所见,角色中给出的目标在基本URL中替换%s.
链接标题取决于元组中的第二项,前缀:
如果前缀为None,则链接标题为完整URL.如果前缀是空字符串,则链接标题是角色内容中给出的部分URL(在本例中为123).如果前缀是非空字符串,则链接标题是部分URL,前缀为前缀 - 在上面的示例中,链接标题将是问题123.您还可以使用生成链接的其他角色支持的常用"显式标题"语法,即:issue:`this issue <123>`.在这种情况下,前缀不相关.
小智 5
我有一个类似的问题,我需要替换图像目标中的 URL。在extlinks作为图像的值时不扩展:target:属性。最终,我编写了一个自定义的 sphinx 转换,它重写了以给定前缀开头的 URL,在我的例子中是http://mybase/. 这是 conf.py 的相关代码:
from sphinx.transforms import SphinxTransform
class ReplaceMyBase(SphinxTransform):
default_priority = 750
prefix = 'http://mybase/'
def apply(self):
from docutils.nodes import reference, Text
baseref = lambda o: (
isinstance(o, reference) and
o.get('refuri', '').startswith(self.prefix))
basetext = lambda o: (
isinstance(o, Text) and o.startswith(self.prefix))
base = self.config.mybase.rstrip('/') + '/'
for node in self.document.traverse(baseref):
target = node['refuri'].replace(self.prefix, base, 1)
node.replace_attr('refuri', target)
for t in node.traverse(basetext):
t1 = Text(t.replace(self.prefix, base, 1), t.rawsource)
t.parent.replace(t, t1)
return
# end of class
def setup(app):
app.add_config_value('mybase', 'https://en.wikipedia.org/wiki', 'env')
app.add_transform(ReplaceMyBase)
return
Run Code Online (Sandbox Code Playgroud)
这将以下第一个源扩展为指向英文维基百科。当 conf.py 设置mybase="https://es.wikipedia.org/wiki"链接将指向西班牙语维基。
* inline link http://mybase/Helianthus
* `link with text <http://mybase/Helianthus>`_
* `link with separate definition`_
* image link |flowerimage|
.. _link with separate definition: http://mybase/Helianthus
.. |flowerimage| image:: https://upload.wikimedia.org/wikipedia/commons/f/f1/Tournesol.png
:target: http://mybase/Helianthus
Run Code Online (Sandbox Code Playgroud)