Substitutions inside links in reST / Sphinx

匿名 (未验证) 提交于 2019-12-03 00:57:01

问题:

I am using Sphinx to document a webservice that will be deployed in different servers. The documentation is full of URL examples for the user to click and they should just work. My problem is that the host, port and deployment root will vary and the documentation will have to be re-generated for every deployment.

I tried defining substitutions like this:

|base_url|/path .. |base_url| replace:: http://localhost:8080 

But the generated HTML is not what I want (doesn't include "/path" in the generated link):

http://localhost:8080/path 

Does anybody know how to work around this?

回答1:

New in Sphinx v1.0:

http://sphinx.pocoo.org/ext/extlinks.html

The extension adds one new config value:

extlinks

This config value must be a dictionary of external sites, mapping unique short alias names to a base URL and a prefix. For example, to create an alias for the above mentioned issues, you would add

extlinks = {'issue':      ('http://bitbucket.org/birkenfeld/sphinx/issue/%s', 'issue ')} 

Now, you can use the alias name as a new role, e.g. :issue:`123`. This then inserts a link to http://bitbucket.org/birkenfeld/sphinx/issue/123. As you can see, the target given in the role is substituted in the base URL in the place of %s.

The link caption depends on the second item in the tuple, the prefix:

:issue:`this issue `. In this case, the prefix is not relevant.



回答2:

Ok, here's how I did it. First, apilinks.py (the Sphinx extension):

from docutils import nodes, utils  def setup(app):     def api_link_role(role, rawtext, text, lineno, inliner, options={},                       content=[]):         ref = app.config.apilinks_base + text         node = nodes.reference(rawtext, utils.unescape(ref), refuri=ref,                                **options)         return [node], []     app.add_config_value('apilinks_base', 'http://localhost/', False)     app.add_role('apilink', api_link_role) 

Now, in conf.py, add 'apilinks' to the extensions list and set an appropriate value for 'apilinks_base' (otherwise, it will default to 'http://localhost/'). My file looks like this:

extensions = ['sphinx.ext.autodoc', 'apilinks'] # lots of other stuff apilinks_base = 'http://host:88/base/' 

Usage:

:apilink:`path` 

Output:

http://host:88/base/path 


回答3:

You can write a Sphinx extension that creates a role like

:apilink:`path`  

and generates the link from that. I never did this, so I can't help more than giving this pointer, sorry. You should try to look at how the various roles are implemented. Many are very similar to what you need, I think.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!