Substitutions inside links in reST / Sphinx

后端 未结 4 1777
忘掉有多难
忘掉有多难 2020-12-25 13:03

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 w

4条回答
  •  猫巷女王i
    2020-12-25 13:35

    I had a similar problem where I needed to substitute also URLs in image targets. The extlinks do not expand when used as a value of image :target: attribute. Eventually I wrote a custom sphinx transformation that rewrites URLs that start with a given prefix, in my case, http://mybase/. Here is a relevant code for 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
    

    This expands the following rst source to point to English wikipedia. When conf.py sets mybase="https://es.wikipedia.org/wiki" the links would point to the Spanish wiki.

    * inline link http://mybase/Helianthus
    * `link with text `_
    * `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
    

提交回复
热议问题